Floating point problems

David Roundy droundy at darcs.net
Wed Aug 30 14:58:10 EDT 2006


On Wed, Aug 30, 2006 at 07:38:35PM +0100, Jamie Brandon wrote:
> I recently defied my supervisor and used Haskell to write my
> coursework instead of C. All went well until I needed floating point
> and started having odd results. As far as I can tell it isn't
> substantially affecting my results but it is rather embarrassing
> after slagging off C so much. Here are some examples:
>         
>         *Main> 0.2 + 0.1
>         0.30000000000000004
>         *Main> 0.200000000000000 + 0.100000000000000000
>         0.30000000000000004
>         *Main> 0.3 + 0.1
>         0.4
>         *Main> 0.2 + 0.1
>         0.30000000000000004
>         *Main> it + 0.1
>         0.4
>         
> I assume this is a result of the discrepancy between binary and decimal
> representations of the numbers. Is there any way around? For a start, it
> would be nice to have a simple way to get 0.1 + 0.2 == 0.3  =  True
>         
> This is with GHC 6.4.1 and GCC 4.0.3

The trouble here is that ghci is printing more digits than it really
ought to be printing.

There's no language I'm aware of in which 0.1 + 0.2 == 0.3  =  True.

With modern processors and compilers there's not even a guarantee
(although the C language makes such a guarantee--it's just not obeyed)
that

double a = 0.1*0.3 + 0.2;
if (a != 0.1*0.3 + 0.2) exit(1);

will work properly.  i.e. if you stick enough code between the
definition of the variable and the comparison, this check may be
failed.  The reason is that intermediate results are commonly stored
at higher than double precision, leading to non-IEEE arithmetic.  It's
sad, but we're stuck with it, as I'm not aware of any compiler that is
capable of generating IEEE arithmetic.

Note that in Haskell you at least have the option of using the
Rational data type, which *will* give you exact arithmetic, as long as
you don't need transcendental functions.
-- 
David Roundy


More information about the Glasgow-haskell-users mailing list