Floating point

Richard A. O'Keefe ok at cs.otago.ac.nz
Tue Dec 17 01:41:35 UTC 2002


Paul Lakin <bitwisetech at attbi.com> was surprised that
	( ( 1.1 + 1.1 + 1.1) / 3.0) = 
	  ( ( 1.1 + 1.1 + 1.1 + 1.1 + 1.1 + 1.1  ) / 6.0 )
	
came out false.

That's floating-point arithmetic for you.  1.1 is not exactly representable.

For comparison, I just compiled and ran this little C program:

#include <stdio.h>

int main(void) {
    double x = (1.1 + 1.1 + 1.1) / 3.0;
    double y = (1.1 + 1.1 + 1.1 + 1.1 + 1.1 + 1.1) / 6.0;
    double d = x - y;

    printf("%.18e == %.18e -> %s;\ndifference = %.18e\n",
            x, y, x == y ? "true" : "false", d);
    return 0;
}

Compiled with lcc, the output was
1.100000000000000089e+00 == 1.100000000000000089e+00 -> true;
difference = 0.000000000000000000e+00
Compiled with gcc, the output was
1.100000000000000089e+00 == 1.099999999999999867e+00 -> false;
difference = 2.220446049250313081e-16
    
The output you got is not 'incorrect', it is one of the outputs
allowed by floating point arithmetic.



More information about the Squeak-dev mailing list