Incorrect runtime behavior involving comparison

Matt Austern austern@isolde.engr.sgi.com
Mon Jan 10 15:40:00 GMT 2000


No.  Floating-point arithmetic obeys different rules than the arithmetic
of real numbers, but it is neither magical nor (on most architectures)
nondeterministic.

It's consistent for 'x > y' and 'y > x' both to be false.  (It
means that x and y are equal, or else that either x or y is NaN.)
It is not consistent for 'x > y' and 'y > x' both to be true,
which is the behavior we're seeing.

Again, this is the program in question:
austern@daim% cat cbug.cc
#include <stdio.h>

struct zone {
  int profit;
  int size;
  int code_expansion() {
    return size;
  }
  double priority() {
    return ((double)profit)/code_expansion();
  }
};

main()
{
 struct zone z1;
 struct zone z2;
 z1.profit = 100;
 z1.size = 3;
 z2.profit = 200;
 z2.size = 6;

#ifdef BUG
 bool t1 = z1.priority() > z2.priority();
 bool t2 = z2.priority() > z1.priority();
#else
 double d1 = z1.priority();
 double d2 = z2.priority();
 bool t1 = d1 > d2;
 bool t2 = d2 > d1;
#endif

 printf("t1 is %s\n", t1 ? "true" : "false");
 printf("t2 is %s\n", t2 ? "true" : "false");
}

The behavior we're seeing is:

austern@daim% g++ -DBUG cbug.cc
austern@daim% a.out
t1 is true
t2 is true

			--Matt Austern


On Jan 10,  8:31pm, Horst von Brand wrote:
> Subject: Re: Incorrect runtime behavior involving comparison
> "Matt Austern" <austern@isolde.engr.sgi.com> said:
> > SYMPTOM:
> > The correct output from the following program is:
> > t1 is false
> > t2 is false
>
> You are comparing two "should be equal" floating point expressions,
> depending on rounding and the phase of the moon, you will get different
> results.
> --
> Horst von Brand                             vonbrand@sleipnir.valparaiso.cl
> Casilla 9G, Viña del Mar, Chile                               +56 32 672616
>-- End of excerpt from Horst von Brand




More information about the Gcc-bugs mailing list