1 % -----------------------------------------------------------------------------
2 % $Id: Numeric.lhs,v 1.9 2000/06/30 13:39:35 simonmar Exp $
4 % (c) The University of Glasgow, 1997-2000
7 \section[Numeric]{Numeric interface}
9 Odds and ends, mostly functions for reading and showing
10 \tr{RealFloat}-like kind of values.
16 ( fromRat -- :: (RealFloat a) => Rational -> a
17 , showSigned -- :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS
18 , readSigned -- :: (Real a) => ReadS a -> ReadS a
19 , showInt -- :: Integral a => a -> ShowS
20 , readInt -- :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
22 , readDec -- :: (Integral a) => ReadS a
23 , readOct -- :: (Integral a) => ReadS a
24 , readHex -- :: (Integral a) => ReadS a
26 , showEFloat -- :: (RealFloat a) => Maybe Int -> a -> ShowS
27 , showFFloat -- :: (RealFloat a) => Maybe Int -> a -> ShowS
28 , showGFloat -- :: (RealFloat a) => Maybe Int -> a -> ShowS
29 , showFloat -- :: (RealFloat a) => a -> ShowS
30 , readFloat -- :: (RealFloat a) => ReadS a
33 , floatToDigits -- :: (RealFloat a) => Integer -> a -> ([Int], Int)
34 , lexDigits -- :: ReadS String
36 -- Implementation checked wrt. Haskell 98 lib report, 1/99.
43 import Prelude -- For dependencies
44 import PrelBase ( Char(..) )
45 import PrelRead -- Lots of things
46 import PrelReal ( showSigned )
47 import PrelFloat ( fromRat, FFFormat(..),
48 formatRealFloat, floatToDigits, showFloat
50 import PrelNum ( ord_0 )
61 showInt :: Integral a => a -> ShowS
63 | i < 0 = error "Numeric.showInt: can't show negative numbers"
67 case quotRem n 10 of { (n', d) ->
68 case chr (ord_0 + fromIntegral d) of { C# c# -> -- stricter than necessary
72 if n' == 0 then r' else go n' r'
76 Controlling the format and precision of floats. The code that
77 implements the formatting itself is in @PrelNum@ to avoid
81 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
82 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
83 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
85 showEFloat d x = showString (formatRealFloat FFExponent d x)
86 showFFloat d x = showString (formatRealFloat FFFixed d x)
87 showGFloat d x = showString (formatRealFloat FFGeneric d x)
93 %*********************************************************
95 All of this code is for Hugs only
96 GHC gets it from PrelFloat!
98 %*********************************************************
101 -- This converts a rational to a floating. This should be used in the
102 -- Fractional instances of Float and Double.
104 fromRat :: (RealFloat a) => Rational -> a
106 if x == 0 then encodeFloat 0 0 -- Handle exceptional cases
107 else if x < 0 then - fromRat' (-x) -- first.
110 -- Conversion process:
111 -- Scale the rational number by the RealFloat base until
112 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
113 -- Then round the rational to an Integer and encode it with the exponent
114 -- that we got from the scaling.
115 -- To speed up the scaling process we compute the log2 of the number to get
116 -- a first guess of the exponent.
117 fromRat' :: (RealFloat a) => Rational -> a
119 where b = floatRadix r
121 (minExp0, _) = floatRange r
122 minExp = minExp0 - p -- the real minimum exponent
123 xMin = toRational (expt b (p-1))
124 xMax = toRational (expt b p)
125 p0 = (integerLogBase b (numerator x) -
126 integerLogBase b (denominator x) - p) `max` minExp
127 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
128 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
129 r = encodeFloat (round x') p'
131 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
132 scaleRat :: Rational -> Int -> Rational -> Rational ->
133 Int -> Rational -> (Rational, Int)
134 scaleRat b minExp xMin xMax p x =
137 else if x >= xMax then
138 scaleRat b minExp xMin xMax (p+1) (x/b)
139 else if x < xMin then
140 scaleRat b minExp xMin xMax (p-1) (x*b)
144 -- Exponentiation with a cache for the most common numbers.
147 expt :: Integer -> Int -> Integer
149 if base == 2 && n >= minExpt && n <= maxExpt then
154 expts :: Array Int Integer
155 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
157 -- Compute the (floor of the) log of i in base b.
158 -- Simplest way would be just divide i by b until it's smaller then b,
159 -- but that would be very slow! We are just slightly more clever.
160 integerLogBase :: Integer -> Integer -> Int
165 -- Try squaring the base first to cut down the number of divisions.
166 let l = 2 * integerLogBase (b*b) i
167 doDiv :: Integer -> Int -> Int
168 doDiv i l = if i < b then l else doDiv (i `div` b) (l+1)
169 in doDiv (i `div` (b^l)) l
172 -- Misc utilities to show integers and floats
174 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
175 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
176 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
177 showFloat :: (RealFloat a) => a -> ShowS
179 showEFloat d x = showString (formatRealFloat FFExponent d x)
180 showFFloat d x = showString (formatRealFloat FFFixed d x)
181 showGFloat d x = showString (formatRealFloat FFGeneric d x)
182 showFloat = showGFloat Nothing
184 -- These are the format types. This type is not exported.
186 data FFFormat = FFExponent | FFFixed | FFGeneric
188 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
189 formatRealFloat fmt decs x = s
193 else if isInfinite x then
194 if x < 0 then "-Infinity" else "Infinity"
195 else if x < 0 || isNegativeZero x then
196 '-' : doFmt fmt (floatToDigits (toInteger base) (-x))
198 doFmt fmt (floatToDigits (toInteger base) x)
200 let ds = map intToDigit is
203 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
210 [d] -> d : ".0e" ++ show (e-1)
211 d:ds -> d : '.' : ds ++ 'e':show (e-1)
213 let dec' = max dec 1 in
215 [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
217 let (ei, is') = roundTo base (dec'+1) is
218 d:ds = map intToDigit
219 (if ei > 0 then init is' else is')
220 in d:'.':ds ++ "e" ++ show (e-1+ei)
224 let f 0 s ds = mk0 s ++ "." ++ mk0 ds
225 f n s "" = f (n-1) (s++"0") ""
226 f n s (d:ds) = f (n-1) (s++[d]) ds
231 let dec' = max dec 0 in
233 let (ei, is') = roundTo base (dec' + e) is
234 (ls, rs) = splitAt (e+ei) (map intToDigit is')
235 in (if null ls then "0" else ls) ++
236 (if null rs then "" else '.' : rs)
238 let (ei, is') = roundTo base dec'
239 (replicate (-e) 0 ++ is)
240 d : ds = map intToDigit
241 (if ei > 0 then is' else 0:is')
244 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
245 roundTo base d is = case f d is of
247 (1, is) -> (1, 1 : is)
248 where b2 = base `div` 2
249 f n [] = (0, replicate n 0)
250 f 0 (i:_) = (if i >= b2 then 1 else 0, [])
252 let (c, ds) = f (d-1) is
254 in if i' == base then (1, 0:ds) else (0, i':ds)
257 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
258 -- by R.G. Burger and R. K. Dybvig, in PLDI 96.
259 -- This version uses a much slower logarithm estimator. It should be improved.
261 -- This function returns a list of digits (Ints in [0..base-1]) and an
264 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
266 floatToDigits _ 0 = ([0], 0)
267 floatToDigits base x =
268 let (f0, e0) = decodeFloat x
269 (minExp0, _) = floatRange x
272 minExp = minExp0 - p -- the real minimum exponent
273 -- Haskell requires that f be adjusted so denormalized numbers
274 -- will have an impossibly low exponent. Adjust for this.
275 (f, e) = let n = minExp - e0
276 in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
282 (f*be*b*2, 2*b, be*b, b)
286 if e > minExp && f == b^(p-1) then
287 (f*b*2, b^(-e+1)*2, b, 1)
289 (f*2, b^(-e)*2, 1, 1)
292 if b==2 && base==10 then
293 -- logBase 10 2 is slightly bigger than 3/10 so
294 -- the following will err on the low side. Ignoring
295 -- the fraction will make it err even more.
296 -- Haskell promises that p-1 <= logBase b f < p.
297 (p - 1 + e0) * 3 `div` 10
299 ceiling ((log (fromInteger (f+1)) +
300 fromInt e * log (fromInteger b)) /
301 log (fromInteger base))
304 if r + mUp <= expt base n * s then n else fixup (n+1)
306 if expt base (-n) * (r + mUp) <= s then n
310 gen ds rn sN mUpN mDnN =
311 let (dn, rn') = (rn * base) `divMod` sN
314 in case (rn' < mDnN', rn' + mUpN' > sN) of
315 (True, False) -> dn : ds
316 (False, True) -> dn+1 : ds
317 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
318 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
321 gen [] r (s * expt base k) mUp mDn
323 let bk = expt base (-k)
324 in gen [] (r * bk) s (mUp * bk) (mDn * bk)
325 in (map toInt (reverse rds), k)