Floats and Doubles

Simon Marlow simonmar@microsoft.com
Tue, 12 Nov 2002 12:53:24 -0000


> I have been using some of the functions of the classes Real and=20
> Fractional and I have observed that with the funcion=20
> "toRational" we can=20
> obtain the fraction that represents a given number. For instance:
> *P2> toRational (5.2::Float)
> 5452595 % 1048576
> Why we obtain this numbers instead of "52 % 10" or "26 % 5"?

Because you asked for the number to be converted to a Float first, and
5.2 can't be represented exactly in a single-precision float.  If you
don't go via Float, you get the exact result:

Prelude> 5.2 :: Rational
26 % 5

> I have also obtained the following results with the functions=20
> "fromRational" and "toRational":
> *P2> (fromRational ((toRational 4) - ( toRational=20
> (5.2::Float) )))::Double
> -1.1999998092651367
> *P2> (fromRational ((toRational 4) - ( toRational=20
> (5.2::Double) )))::Double
> -1.2000000000000002
> *P2> (fromRational ((toRational 4) - ( toRational 5.2 )))
> -1.2000000000000002
> *P2> (fromRational ((toRational 4) - ( toRational=20
> (5.2::Float) )))::Float
> -1.1999998

These are all symptoms of rounding.

Cheers,
	Simon