[Haskell-cafe] about integer and float operations
Richard O'Keefe
ok at cs.otago.ac.nz
Wed Feb 4 21:41:27 EST 2009
On 5 Feb 2009, at 10:38 am, Manlio Perillo wrote:
> I'm looking for an exact integer division that avoids overflows, if
> possible.
What this sounds like to me is a request that the Prelude
function 'fromRational' should work well. Since
"The floating point literal f is equivalent to
fromRational (n Ratio.% d), where fromRational is a method in class
Fractional and Ratio.%constructs a rational from two integers,
as defined in the Ratio library. The integers n and d are chosen
so that n/d = f."
If you cannot divide two Integers n, d accurately using
(fromRational (n Ratio.% d) :: Double)
that casts doubt on the trustworthiness of floating point literals.
Suppose we have a function
decodeIntegerAsFloat :: RealFloat a => Integer -> (Integer,a)
such that if (s,m) = integer_to_scaled_float x
then either x = 0 and s = 0 and m = 0
or x = m * 2**s (mathematically) and abs m \in [0.5,1.0).
Then
integer_ratio_as_float :: Floating a => Integer -> Integer -> a
integer_ratio_as_float p q = (mp/mq)*(2.0^(sp-sq))
where (sp,mp) = decodeIntegerAsFloat p
(sq,mq) = decodeIntegerAsFloat q
You'd actually use scaleFloat; if the difference sp-sq is outside
the range of Int the answer is going to be a signed zero or a signed
infinity anyway. decodeIntegerAsFloat would sit very well in the
RealFloat class alongside its model, decodeFloat. It has other uses.
For example, you can use it to compute logarithms of Integers with
much less worry about overflow.
More information about the Haskell-Cafe
mailing list