lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

"Rici Lake" <> wrote in message">

On 26-Dec-06, at 11:51 PM, Joe Smith wrote:

"Luiz Henrique de Figueiredo" <> wrote in message">
Directly compairing floating point numbers for equality is *always* a bad

Only if the numbers are supposed to be the same number but are the result
of two different computations.

For example, you can find that a floating point value which is not a
NaN is not equal to itself.

I find this very surprising. And possibily wrong, ie against IEEE 754.
The explanation that followed made no sense to me. It would make sense for floating point values held in *different* variables, but not for the *same*
variable. It seems to me that the gcc docs is spreading unnecessary FUD.
But I must be missing something...

I've heard this same explanation elsewere too. (Somebody saw this problem in production code). Apparently, the registers used in the FPU are oversized, and thus calculations performed there-in have morie bits than the datatype should. Thus when compairing a value in the register to the truncated value in the memory, they can be non-equal. I lack access to the IEEE 754 standard, and cannot make heads or tails of much of the ISO C standard when it talks about floating point numbers, so I'm not certain if this behavior violates either standard, but I've seen this documented more than once.

On the other hand, it is highly unlikely that the code listed would ever be affected by this, but it is still troubling.

I can't see how (x == x) could yield the incorrect answer. The warning that a number may not be equal to "itself" should probably be interpreted as meaning that two different computations of the same value, even if they are textually identical, may result in different answers. Consequently, the code:

No. What they are warning is that

may fail, even for !isnan(y)

Lets say y is a 10-byte extended precision double in the FPU.
For some reason, the compiler decides that 'x' should be storred in memory.
So x is set to a 8-byte representation of y, created by truncation. The extra 2 bytes of precision means that
x and y do not compare equally.

I just compiled and ran this code (similar to the example baove, but reverse variable names) and had the assert fail:
#include <assert.h>
int main()
 register double x;
 double y;
 x=x * 0.5 - 1.25e-11;