Comparison Failure on Linux
: Suppose we have the following code fragment:
: double d1 = (a + b)/2.0;
: double d2 = (a + b)/2.0; /* with identical a and identical b */
: Is d1 == d2 ALWAYS true? I found that it is not.
Assuming you are talking about Linux on an Intel x86 machine, no.
The results depend upon the level of optimization you choose, and
other code near the above.
The comparison may fail if gcc is able to keep one of d1 or d2 in
an FPU register but not the other. Linux operates the FPU in 64 bit
precision mode. The expression (a + b)/2.0 will always be computed
to 64 bit precision. A "double" has 53 bit precision.
When the comparison is performed, it may be comparing a 64 bit precision
result (the number which gcc has been able to keep in an FPU register)
with a 53 bit precision result (the number which gcc had to store in
memory, converting to 53 bit precision, and later retrieve). The two
numbers will usually not be equal.
The moral of the story is to "never rely upon exact comparisons of
floating point numbers" (unless you *really* know what is happening).
: I am using gcc-2.7.2 on Linux 1.2.13. It seems that d1 and d2 can differ by
: an multiplicative factor (1.0 +/- DBL_EPSILON). Is this a normal behavior?
The difference is not DBL_EPSILON, but something less than that.