[Haskell-cafe] Exception for NaN

Daniel Fischer daniel.is.fischer at googlemail.com
Tue May 17 00:53:39 CEST 2011


On Tuesday 17 May 2011 00:22:02, Alexey Khudyakov wrote:
> On 16.05.2011 22:51, Casey McCann wrote:
> > How so? Equality on floating point values other than NaN works just
> > fine and behaves as expected. It's just that they violate all sorts of
> > algebraic laws when arithmetic is involved so sequences of operations
> > that should be equivalent aren't, in ways that are highly dependent on
> > the values being operated on.
> 
> Well not nessesarily. FPU may store intermediate values with more bits
> than in memory representation. When value is moved to memory from
> registers it loses some accuracy. So when you compare doubles for
> equality you may get true or false depending on compiler optimizations.

Yes. Well, sophistically, no - in that case, you're not comparing doubles 
;)
In theory, you have a well-behaved equality and ordering for IEEE-754 
floating-point values which aren't NaNs or -0.0 (that too messes some 
things up).
In practice, however, you're often not dealing with 32-bit floats or 64-bit 
doubles but with what the FPU uses internally and that can also mess things 
up big time.

> 
> For example following C program prints 0 if compiled without
> optimitizations

Not necessarily. It will (almost certainly, I don't think gcc changed that) 
print 1 if it's compiled with the pessimisation -ffloat-store.

And that's how one gets predictable behaviour of ==, < etc on floating 
point types, one must make sure that the operands of the comparison are 
fetched from memory and not from an FPU register. But that's not always 
easy.

> and 1 with -O2. (gcc 4.6.1)
> 
> #include <math.h>
> #include <stdlib.h>
> #include <stdio.h>
> 
> int main(int argc, char** argv)
> {
>      double y = 1;
>      double x = tan(y);
>      printf("%i\n", x == tan(y));
>      return 0;
> }
> 
> At any rate comparing floating points values for equality is asking for
> trouble.

I wouldn't go that far, but it's not something to do light-heartedly, there 
be dragons.



More information about the Haskell-Cafe mailing list