1 -----------------------------------------------------------------------------
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/core/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
11 -- $Id: Numeric.hs,v 1.3 2002/01/02 14:40:09 simonmar Exp $
13 -- Odds and ends, mostly functions for reading and showing
14 -- RealFloat-like kind of values.
16 -----------------------------------------------------------------------------
20 fromRat, -- :: (RealFloat a) => Rational -> a
21 showSigned, -- :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS
22 readSigned, -- :: (Real a) => ReadS a -> ReadS a
23 showInt, -- :: Integral a => a -> ShowS
24 readInt, -- :: (Integral a) => a -> (Char -> Bool)
25 -- -> (Char -> Int) -> ReadS a
27 readDec, -- :: (Integral a) => ReadS a
28 readOct, -- :: (Integral a) => ReadS a
29 readHex, -- :: (Integral a) => ReadS a
31 showHex, -- :: Integral a => a -> ShowS
32 showOct, -- :: Integral a => a -> ShowS
33 showBin, -- :: Integral a => a -> ShowS
35 showEFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS
36 showFFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS
37 showGFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS
38 showFloat, -- :: (RealFloat a) => a -> ShowS
39 readFloat, -- :: (RealFloat a) => ReadS a
42 floatToDigits, -- :: (RealFloat a) => Integer -> a -> ([Int], Int)
43 lexDigits, -- :: ReadS String
45 -- general purpose number->string converter.
46 showIntAtBase, -- :: Integral a
48 -- -> (a -> Char) -- digit to char
49 -- -> a -- number to show.
53 import Prelude -- For dependencies
56 #ifdef __GLASGOW_HASKELL__
57 import GHC.Base ( Char(..), unsafeChr )
59 import GHC.Real ( showSigned )
67 #ifdef __GLASGOW_HASKELL__
68 showInt :: Integral a => a -> ShowS
70 | n < 0 = error "Numeric.showInt: can't show negative numbers"
74 | n < 10 = case unsafeChr (ord '0' + fromIntegral n) of
76 | otherwise = case unsafeChr (ord '0' + fromIntegral r) of
77 c@(C# _) -> go q (c:cs)
79 (q,r) = n `quotRem` 10
81 -- Controlling the format and precision of floats. The code that
82 -- implements the formatting itself is in @PrelNum@ to avoid
83 -- mutual module deps.
85 {-# SPECIALIZE showEFloat ::
86 Maybe Int -> Float -> ShowS,
87 Maybe Int -> Double -> ShowS #-}
88 {-# SPECIALIZE showFFloat ::
89 Maybe Int -> Float -> ShowS,
90 Maybe Int -> Double -> ShowS #-}
91 {-# SPECIALIZE showGFloat ::
92 Maybe Int -> Float -> ShowS,
93 Maybe Int -> Double -> ShowS #-}
95 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
96 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
97 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
99 showEFloat d x = showString (formatRealFloat FFExponent d x)
100 showFFloat d x = showString (formatRealFloat FFFixed d x)
101 showGFloat d x = showString (formatRealFloat FFGeneric d x)
105 -- This converts a rational to a floating. This should be used in the
106 -- Fractional instances of Float and Double.
108 fromRat :: (RealFloat a) => Rational -> a
110 if x == 0 then encodeFloat 0 0 -- Handle exceptional cases
111 else if x < 0 then - fromRat' (-x) -- first.
114 -- Conversion process:
115 -- Scale the rational number by the RealFloat base until
116 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
117 -- Then round the rational to an Integer and encode it with the exponent
118 -- that we got from the scaling.
119 -- To speed up the scaling process we compute the log2 of the number to get
120 -- a first guess of the exponent.
121 fromRat' :: (RealFloat a) => Rational -> a
123 where b = floatRadix r
125 (minExp0, _) = floatRange r
126 minExp = minExp0 - p -- the real minimum exponent
127 xMin = toRational (expt b (p-1))
128 xMax = toRational (expt b p)
129 p0 = (integerLogBase b (numerator x) -
130 integerLogBase b (denominator x) - p) `max` minExp
131 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
132 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
133 r = encodeFloat (round x') p'
135 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
136 scaleRat :: Rational -> Int -> Rational -> Rational ->
137 Int -> Rational -> (Rational, Int)
138 scaleRat b minExp xMin xMax p x =
141 else if x >= xMax then
142 scaleRat b minExp xMin xMax (p+1) (x/b)
143 else if x < xMin then
144 scaleRat b minExp xMin xMax (p-1) (x*b)
148 -- Exponentiation with a cache for the most common numbers.
151 expt :: Integer -> Int -> Integer
153 if base == 2 && n >= minExpt && n <= maxExpt then
158 expts :: Array Int Integer
159 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
161 -- Compute the (floor of the) log of i in base b.
162 -- Simplest way would be just divide i by b until it's smaller then b,
163 -- but that would be very slow! We are just slightly more clever.
164 integerLogBase :: Integer -> Integer -> Int
169 -- Try squaring the base first to cut down the number of divisions.
170 let l = 2 * integerLogBase (b*b) i
171 doDiv :: Integer -> Int -> Int
172 doDiv i l = if i < b then l else doDiv (i `div` b) (l+1)
173 in doDiv (i `div` (b^l)) l
176 -- Misc utilities to show integers and floats
178 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
179 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
180 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
181 showFloat :: (RealFloat a) => a -> ShowS
183 showEFloat d x = showString (formatRealFloat FFExponent d x)
184 showFFloat d x = showString (formatRealFloat FFFixed d x)
185 showGFloat d x = showString (formatRealFloat FFGeneric d x)
186 showFloat = showGFloat Nothing
188 -- These are the format types. This type is not exported.
190 data FFFormat = FFExponent | FFFixed | FFGeneric
192 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
193 formatRealFloat fmt decs x = s
197 else if isInfinite x then
198 if x < 0 then "-Infinity" else "Infinity"
199 else if x < 0 || isNegativeZero x then
200 '-' : doFmt fmt (floatToDigits (toInteger base) (-x))
202 doFmt fmt (floatToDigits (toInteger base) x)
204 let ds = map intToDigit is
207 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
214 [d] -> d : ".0e" ++ show (e-1)
215 d:ds -> d : '.' : ds ++ 'e':show (e-1)
217 let dec' = max dec 1 in
219 [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
221 let (ei, is') = roundTo base (dec'+1) is
222 d:ds = map intToDigit
223 (if ei > 0 then init is' else is')
224 in d:'.':ds ++ "e" ++ show (e-1+ei)
228 let f 0 s ds = mk0 s ++ "." ++ mk0 ds
229 f n s "" = f (n-1) (s++"0") ""
230 f n s (d:ds) = f (n-1) (s++[d]) ds
235 let dec' = max dec 0 in
237 let (ei, is') = roundTo base (dec' + e) is
238 (ls, rs) = splitAt (e+ei) (map intToDigit is')
239 in (if null ls then "0" else ls) ++
240 (if null rs then "" else '.' : rs)
242 let (ei, is') = roundTo base dec'
243 (replicate (-e) 0 ++ is)
244 d : ds = map intToDigit
245 (if ei > 0 then is' else 0:is')
248 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
249 roundTo base d is = case f d is of
251 (1, is) -> (1, 1 : is)
252 where b2 = base `div` 2
253 f n [] = (0, replicate n 0)
254 f 0 (i:_) = (if i >= b2 then 1 else 0, [])
256 let (c, ds) = f (d-1) is
258 in if i' == base then (1, 0:ds) else (0, i':ds)
261 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
262 -- by R.G. Burger and R. K. Dybvig, in PLDI 96.
263 -- This version uses a much slower logarithm estimator. It should be improved.
265 -- This function returns a list of digits (Ints in [0..base-1]) and an
268 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
270 floatToDigits _ 0 = ([0], 0)
271 floatToDigits base x =
272 let (f0, e0) = decodeFloat x
273 (minExp0, _) = floatRange x
276 minExp = minExp0 - p -- the real minimum exponent
277 -- Haskell requires that f be adjusted so denormalized numbers
278 -- will have an impossibly low exponent. Adjust for this.
279 (f, e) = let n = minExp - e0
280 in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
286 (f*be*b*2, 2*b, be*b, b)
290 if e > minExp && f == b^(p-1) then
291 (f*b*2, b^(-e+1)*2, b, 1)
293 (f*2, b^(-e)*2, 1, 1)
296 if b==2 && base==10 then
297 -- logBase 10 2 is slightly bigger than 3/10 so
298 -- the following will err on the low side. Ignoring
299 -- the fraction will make it err even more.
300 -- Haskell promises that p-1 <= logBase b f < p.
301 (p - 1 + e0) * 3 `div` 10
303 ceiling ((log (fromInteger (f+1)) +
304 fromIntegral e * log (fromInteger b)) /
305 log (fromInteger base))
308 if r + mUp <= expt base n * s then n else fixup (n+1)
310 if expt base (-n) * (r + mUp) <= s then n
314 gen ds rn sN mUpN mDnN =
315 let (dn, rn') = (rn * base) `divMod` sN
318 in case (rn' < mDnN', rn' + mUpN' > sN) of
319 (True, False) -> dn : ds
320 (False, True) -> dn+1 : ds
321 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
322 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
325 gen [] r (s * expt base k) mUp mDn
327 let bk = expt base (-k)
328 in gen [] (r * bk) s (mUp * bk) (mDn * bk)
329 in (map fromIntegral (reverse rds), k)
332 -- ---------------------------------------------------------------------------
333 -- Integer printing functions
335 showIntAtBase :: Integral a => a -> (a -> Char) -> a -> ShowS
336 showIntAtBase base toChr n r
337 | n < 0 = error ("Numeric.showIntAtBase: applied to negative number " ++ show n)
339 case quotRem n base of { (n', d) ->
341 seq c $ -- stricter than necessary
345 if n' == 0 then r' else showIntAtBase base toChr n' r'
348 showHex :: Integral a => a -> ShowS
351 showIntAtBase 16 (toChrHex) n r
354 | d < 10 = chr (ord '0' + fromIntegral d)
355 | otherwise = chr (ord 'a' + fromIntegral (d - 10))
357 showOct :: Integral a => a -> ShowS
360 showIntAtBase 8 (toChrOct) n r
361 where toChrOct d = chr (ord '0' + fromIntegral d)
363 showBin :: Integral a => a -> ShowS
366 showIntAtBase 2 (toChrOct) n r
367 where toChrOct d = chr (ord '0' + fromIntegral d)