Integers too big for floats

From HaskellWiki
Revision as of 16:04, 6 February 2009 by Lemming (talk | contribs) (describe the problem)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Although floating point types can represent a large range of magnitudes, you will sometimes have to cope with integers that are larger than what is representable by Double.

Dividing large integers to floats


factorial :: (Enum a, Num a) => a -> a
factorial k = product [1..k]

You will find that factorial 777 is not representable by Double. However it is representable by an Integer. You will find that factorial 777 / factorial 778 is representable as Double but not as Integer, but the temporary results are representable by Integers and not by Doubles. Is there a variant of division which accepts big integers and emits floating point numbers?

Actually you can represent the fraction factorial 777 / factorial 778 as Rational and convert that to a floating point number:

fromRational (factorial 777 % factorial 778)

Fortunately fromRational is clever enough to handle big numerators and denominators.

But there is an efficiency problem: Before fromRational can perform the imprecise division, the % operator will cancel the fraction precisely. You may use the Rational constructor <hask:>%</hask> instead. However that's a hack, since it is not sure that other operations work well on non-cancelled fractions. You had to import GHC.Real.

See also