[Haskell-cafe] Exception for NaN

Alexey Khudyakov alexey.skladnoy at gmail.com
Tue May 17 00:22:02 CEST 2011


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.

For example following C program prints 0 if compiled without 
optimitizations 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.



More information about the Haskell-Cafe mailing list