2 % (c) The AQUA Project, Glasgow University, 1997-99
4 \section[Numeric]{Numeric interface}
6 Odds and ends, mostly functions for reading and showing
7 \tr{RealFloat}-like kind of values.
11 {-# OPTIONS -fno-implicit-prelude #-}
14 ( fromRat -- :: (RealFloat a) => Rational -> a
15 , showSigned -- :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS
16 , readSigned -- :: (Real a) => ReadS a -> ReadS a
17 , showInt -- :: Integral a => a -> ShowS
18 , readInt -- :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
20 , readDec -- :: (Integral a) => ReadS a
21 , readOct -- :: (Integral a) => ReadS a
22 , readHex -- :: (Integral a) => ReadS a
24 , showEFloat -- :: (RealFloat a) => Maybe Int -> a -> ShowS
25 , showFFloat -- :: (RealFloat a) => Maybe Int -> a -> ShowS
26 , showGFloat -- :: (RealFloat a) => Maybe Int -> a -> ShowS
27 , showFloat -- :: (RealFloat a) => a -> ShowS
28 , readFloat -- :: (RealFloat a) => ReadS a
31 , floatToDigits -- :: (RealFloat a) => Integer -> a -> ([Int], Int)
32 , lexDigits -- :: ReadS String
34 -- Implementation checked wrt. Haskell 98 lib report, 1/99.
45 import PrelErr ( error )
55 showInt :: Integral a => a -> ShowS
57 | i < 0 = error "Numeric.showInt: can't show negative numbers"
61 case quotRem n 10 of { (n', d) ->
62 case chr (ord_0 + fromIntegral d) of { C# c# -> -- stricter than necessary
66 if n' == 0 then r' else go n' r'
70 Controlling the format and precision of floats. The code that
71 implements the formatting itself is in @PrelNum@ to avoid
75 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
76 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
77 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
79 showEFloat d x = showString (formatRealFloat FFExponent d x)
80 showFFloat d x = showString (formatRealFloat FFFixed d x)
81 showGFloat d x = showString (formatRealFloat FFGeneric d x)
87 -- This converts a rational to a floating. This should be used in the
88 -- Fractional instances of Float and Double.
90 fromRat :: (RealFloat a) => Rational -> a
92 if x == 0 then encodeFloat 0 0 -- Handle exceptional cases
93 else if x < 0 then - fromRat' (-x) -- first.
96 -- Conversion process:
97 -- Scale the rational number by the RealFloat base until
98 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
99 -- Then round the rational to an Integer and encode it with the exponent
100 -- that we got from the scaling.
101 -- To speed up the scaling process we compute the log2 of the number to get
102 -- a first guess of the exponent.
103 fromRat' :: (RealFloat a) => Rational -> a
105 where b = floatRadix r
107 (minExp0, _) = floatRange r
108 minExp = minExp0 - p -- the real minimum exponent
109 xMin = toRational (expt b (p-1))
110 xMax = toRational (expt b p)
111 p0 = (integerLogBase b (numerator x) -
112 integerLogBase b (denominator x) - p) `max` minExp
113 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
114 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
115 r = encodeFloat (round x') p'
117 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
118 scaleRat :: Rational -> Int -> Rational -> Rational ->
119 Int -> Rational -> (Rational, Int)
120 scaleRat b minExp xMin xMax p x =
123 else if x >= xMax then
124 scaleRat b minExp xMin xMax (p+1) (x/b)
125 else if x < xMin then
126 scaleRat b minExp xMin xMax (p-1) (x*b)
130 -- Exponentiation with a cache for the most common numbers.
133 expt :: Integer -> Int -> Integer
135 if base == 2 && n >= minExpt && n <= maxExpt then
140 expts :: Array Int Integer
141 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
143 -- Compute the (floor of the) log of i in base b.
144 -- Simplest way would be just divide i by b until it's smaller then b,
145 -- but that would be very slow! We are just slightly more clever.
146 integerLogBase :: Integer -> Integer -> Int
151 -- Try squaring the base first to cut down the number of divisions.
152 let l = 2 * integerLogBase (b*b) i
153 doDiv :: Integer -> Int -> Int
154 doDiv i l = if i < b then l else doDiv (i `div` b) (l+1)
155 in doDiv (i `div` (b^l)) l
158 -- Misc utilities to show integers and floats
160 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
161 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
162 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
163 showFloat :: (RealFloat a) => a -> ShowS
165 showEFloat d x = showString (formatRealFloat FFExponent d x)
166 showFFloat d x = showString (formatRealFloat FFFixed d x)
167 showGFloat d x = showString (formatRealFloat FFGeneric d x)
168 showFloat = showGFloat Nothing
170 -- These are the format types. This type is not exported.
172 data FFFormat = FFExponent | FFFixed | FFGeneric
174 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
175 formatRealFloat fmt decs x = s
179 else if isInfinite x then
180 if x < 0 then "-Infinity" else "Infinity"
181 else if x < 0 || isNegativeZero x then
182 '-' : doFmt fmt (floatToDigits (toInteger base) (-x))
184 doFmt fmt (floatToDigits (toInteger base) x)
186 let ds = map intToDigit is
189 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
196 [d] -> d : ".0e" ++ show (e-1)
197 d:ds -> d : '.' : ds ++ 'e':show (e-1)
199 let dec' = max dec 1 in
201 [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
203 let (ei, is') = roundTo base (dec'+1) is
204 d:ds = map intToDigit
205 (if ei > 0 then init is' else is')
206 in d:'.':ds ++ "e" ++ show (e-1+ei)
210 let f 0 s ds = mk0 s ++ "." ++ mk0 ds
211 f n s "" = f (n-1) (s++"0") ""
212 f n s (d:ds) = f (n-1) (s++[d]) ds
217 let dec' = max dec 0 in
219 let (ei, is') = roundTo base (dec' + e) is
220 (ls, rs) = splitAt (e+ei) (map intToDigit is')
221 in (if null ls then "0" else ls) ++
222 (if null rs then "" else '.' : rs)
224 let (ei, is') = roundTo base dec'
225 (replicate (-e) 0 ++ is)
226 d : ds = map intToDigit
227 (if ei > 0 then is' else 0:is')
230 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
231 roundTo base d is = case f d is of
233 (1, is) -> (1, 1 : is)
234 where b2 = base `div` 2
235 f n [] = (0, replicate n 0)
236 f 0 (i:_) = (if i >= b2 then 1 else 0, [])
238 let (c, ds) = f (d-1) is
240 in if i' == base then (1, 0:ds) else (0, i':ds)
243 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
244 -- by R.G. Burger and R. K. Dybvig, in PLDI 96.
245 -- This version uses a much slower logarithm estimator. It should be improved.
247 -- This function returns a list of digits (Ints in [0..base-1]) and an
250 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
252 floatToDigits _ 0 = ([0], 0)
253 floatToDigits base x =
254 let (f0, e0) = decodeFloat x
255 (minExp0, _) = floatRange x
258 minExp = minExp0 - p -- the real minimum exponent
259 -- Haskell requires that f be adjusted so denormalized numbers
260 -- will have an impossibly low exponent. Adjust for this.
261 (f, e) = let n = minExp - e0
262 in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
268 (f*be*b*2, 2*b, be*b, b)
272 if e > minExp && f == b^(p-1) then
273 (f*b*2, b^(-e+1)*2, b, 1)
275 (f*2, b^(-e)*2, 1, 1)
278 if b==2 && base==10 then
279 -- logBase 10 2 is slightly bigger than 3/10 so
280 -- the following will err on the low side. Ignoring
281 -- the fraction will make it err even more.
282 -- Haskell promises that p-1 <= logBase b f < p.
283 (p - 1 + e0) * 3 `div` 10
285 ceiling ((log (fromInteger (f+1)) +
286 fromInt e * log (fromInteger b)) /
287 log (fromInteger base))
290 if r + mUp <= expt base n * s then n else fixup (n+1)
292 if expt base (-n) * (r + mUp) <= s then n
296 gen ds rn sN mUpN mDnN =
297 let (dn, rn') = (rn * base) `divMod` sN
300 in case (rn' < mDnN', rn' + mUpN' > sN) of
301 (True, False) -> dn : ds
302 (False, True) -> dn+1 : ds
303 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
304 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
307 gen [] r (s * expt base k) mUp mDn
309 let bk = expt base (-k)
310 in gen [] (r * bk) s (mUp * bk) (mDn * bk)
311 in (map toInt (reverse rds), k)