Arbitrary precision reals?

Tom Pledger Tom.Pledger@peace.com
Tue, 25 Mar 2003 09:13:30 +1200


Niall Dalton writes:
 | Hi,
 | 
 | Its been a while since I've been using Haskell seriously, so I might simply
 | have overlooked the answer..
 | 
 | Is there an arbitrary precision real number library available for Haskell?
 | IIRC, atleast GHC uses the GMP library, but only for integers?

Hi.

There's the Ratio library, which can be used to make arbitrary
precision rationals from arbitrary precision integers.  But it doesn't
provide arbitrary *finite* precision implementations of imprecise
functions such as exp, so I suspect it's not quite what you're after.

I don't know whether arbitrary precision reals have been done in
Haskell, but here's one of the issues...

The floating point part of the GNU mp library looks difficult to fit
into Haskell's numeric classes, because the type signatures in class
Floating don't include a how-much-precision-do-you-want parameter.

For example, Haskell's

    sqrt :: Floating a => a -> a

may look like it matches GNU mp's

    void mpf_sqrt (mpf_t rop, mpf_t op)

but the result pointer rop also provides the precision argument, which
was prepared earlier by some impure stateful action such as

    void mpf_set_default_prec (unsigned long int prec)

I can see three ways around this, but they're all rather fiddly.

  - Write a nonstandard version of Haskell's Floating class,
    introducing an explicit how-much-precision-do-you-want parameter.

  - Declare a separate Floating instance for each fixed precision
    level you want to use, e.g. instance Floating GNU_mpf_t_with_300bits.

  - Declare a data type which pairs a GNU mpf_t with a number of bits,
    and declare a Floating instance for this data type, inferring the
    required precision of the result from the precision of the
    arguments.  This gets into trouble when there are no arguments: pi
    would presumably have to have fixed precision.  Although you could
    always ignore it in favour of something like

        (4 `withBits` 300) * atan (1 `withBits` 300)

Regards,
Tom



http://haskell.org/onlinereport/ratio.html
http://www.swox.com/gmp/manual/Float-Arithmetic.html#Float%20Arithmetic
http://www.swox.com/gmp/manual/Initializing-Floats.html#Initializing%20Floats