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.2 2001/08/02 13:30:36 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 {- -- left out for now, as we can only export the H98 interface
32 showHex, -- :: Integral a => a -> ShowS
33 showOct, -- :: Integral a => a -> ShowS
34 showBin, -- :: Integral a => a -> ShowS
37 showEFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS
38 showFFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS
39 showGFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS
40 showFloat, -- :: (RealFloat a) => a -> ShowS
41 readFloat, -- :: (RealFloat a) => ReadS a
44 floatToDigits, -- :: (RealFloat a) => Integer -> a -> ([Int], Int)
45 lexDigits, -- :: ReadS String
47 {- -- left out for now, as we can only export the H98 interface
48 -- general purpose number->string converter.
49 showIntAtBase, -- :: Integral a
51 -- -> (a -> Char) -- digit to char
52 -- -> a -- number to show.
57 import Prelude -- For dependencies
60 #ifdef __GLASGOW_HASKELL__
61 import GHC.Base ( Char(..), unsafeChr )
63 import GHC.Real ( showSigned )
71 #ifdef __GLASGOW_HASKELL__
72 showInt :: Integral a => a -> ShowS
74 | n < 0 = error "Numeric.showInt: can't show negative numbers"
78 | n < 10 = case unsafeChr (ord '0' + fromIntegral n) of
80 | otherwise = case unsafeChr (ord '0' + fromIntegral r) of
81 c@(C# _) -> go q (c:cs)
83 (q,r) = n `quotRem` 10
85 -- Controlling the format and precision of floats. The code that
86 -- implements the formatting itself is in @PrelNum@ to avoid
87 -- mutual module deps.
89 {-# SPECIALIZE showEFloat ::
90 Maybe Int -> Float -> ShowS,
91 Maybe Int -> Double -> ShowS #-}
92 {-# SPECIALIZE showFFloat ::
93 Maybe Int -> Float -> ShowS,
94 Maybe Int -> Double -> ShowS #-}
95 {-# SPECIALIZE showGFloat ::
96 Maybe Int -> Float -> ShowS,
97 Maybe Int -> Double -> ShowS #-}
99 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
100 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
101 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
103 showEFloat d x = showString (formatRealFloat FFExponent d x)
104 showFFloat d x = showString (formatRealFloat FFFixed d x)
105 showGFloat d x = showString (formatRealFloat FFGeneric d x)
109 -- This converts a rational to a floating. This should be used in the
110 -- Fractional instances of Float and Double.
112 fromRat :: (RealFloat a) => Rational -> a
114 if x == 0 then encodeFloat 0 0 -- Handle exceptional cases
115 else if x < 0 then - fromRat' (-x) -- first.
118 -- Conversion process:
119 -- Scale the rational number by the RealFloat base until
120 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
121 -- Then round the rational to an Integer and encode it with the exponent
122 -- that we got from the scaling.
123 -- To speed up the scaling process we compute the log2 of the number to get
124 -- a first guess of the exponent.
125 fromRat' :: (RealFloat a) => Rational -> a
127 where b = floatRadix r
129 (minExp0, _) = floatRange r
130 minExp = minExp0 - p -- the real minimum exponent
131 xMin = toRational (expt b (p-1))
132 xMax = toRational (expt b p)
133 p0 = (integerLogBase b (numerator x) -
134 integerLogBase b (denominator x) - p) `max` minExp
135 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
136 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
137 r = encodeFloat (round x') p'
139 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
140 scaleRat :: Rational -> Int -> Rational -> Rational ->
141 Int -> Rational -> (Rational, Int)
142 scaleRat b minExp xMin xMax p x =
145 else if x >= xMax then
146 scaleRat b minExp xMin xMax (p+1) (x/b)
147 else if x < xMin then
148 scaleRat b minExp xMin xMax (p-1) (x*b)
152 -- Exponentiation with a cache for the most common numbers.
155 expt :: Integer -> Int -> Integer
157 if base == 2 && n >= minExpt && n <= maxExpt then
162 expts :: Array Int Integer
163 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
165 -- Compute the (floor of the) log of i in base b.
166 -- Simplest way would be just divide i by b until it's smaller then b,
167 -- but that would be very slow! We are just slightly more clever.
168 integerLogBase :: Integer -> Integer -> Int
173 -- Try squaring the base first to cut down the number of divisions.
174 let l = 2 * integerLogBase (b*b) i
175 doDiv :: Integer -> Int -> Int
176 doDiv i l = if i < b then l else doDiv (i `div` b) (l+1)
177 in doDiv (i `div` (b^l)) l
180 -- Misc utilities to show integers and floats
182 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
183 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
184 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
185 showFloat :: (RealFloat a) => a -> ShowS
187 showEFloat d x = showString (formatRealFloat FFExponent d x)
188 showFFloat d x = showString (formatRealFloat FFFixed d x)
189 showGFloat d x = showString (formatRealFloat FFGeneric d x)
190 showFloat = showGFloat Nothing
192 -- These are the format types. This type is not exported.
194 data FFFormat = FFExponent | FFFixed | FFGeneric
196 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
197 formatRealFloat fmt decs x = s
201 else if isInfinite x then
202 if x < 0 then "-Infinity" else "Infinity"
203 else if x < 0 || isNegativeZero x then
204 '-' : doFmt fmt (floatToDigits (toInteger base) (-x))
206 doFmt fmt (floatToDigits (toInteger base) x)
208 let ds = map intToDigit is
211 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
218 [d] -> d : ".0e" ++ show (e-1)
219 d:ds -> d : '.' : ds ++ 'e':show (e-1)
221 let dec' = max dec 1 in
223 [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
225 let (ei, is') = roundTo base (dec'+1) is
226 d:ds = map intToDigit
227 (if ei > 0 then init is' else is')
228 in d:'.':ds ++ "e" ++ show (e-1+ei)
232 let f 0 s ds = mk0 s ++ "." ++ mk0 ds
233 f n s "" = f (n-1) (s++"0") ""
234 f n s (d:ds) = f (n-1) (s++[d]) ds
239 let dec' = max dec 0 in
241 let (ei, is') = roundTo base (dec' + e) is
242 (ls, rs) = splitAt (e+ei) (map intToDigit is')
243 in (if null ls then "0" else ls) ++
244 (if null rs then "" else '.' : rs)
246 let (ei, is') = roundTo base dec'
247 (replicate (-e) 0 ++ is)
248 d : ds = map intToDigit
249 (if ei > 0 then is' else 0:is')
252 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
253 roundTo base d is = case f d is of
255 (1, is) -> (1, 1 : is)
256 where b2 = base `div` 2
257 f n [] = (0, replicate n 0)
258 f 0 (i:_) = (if i >= b2 then 1 else 0, [])
260 let (c, ds) = f (d-1) is
262 in if i' == base then (1, 0:ds) else (0, i':ds)
265 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
266 -- by R.G. Burger and R. K. Dybvig, in PLDI 96.
267 -- This version uses a much slower logarithm estimator. It should be improved.
269 -- This function returns a list of digits (Ints in [0..base-1]) and an
272 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
274 floatToDigits _ 0 = ([0], 0)
275 floatToDigits base x =
276 let (f0, e0) = decodeFloat x
277 (minExp0, _) = floatRange x
280 minExp = minExp0 - p -- the real minimum exponent
281 -- Haskell requires that f be adjusted so denormalized numbers
282 -- will have an impossibly low exponent. Adjust for this.
283 (f, e) = let n = minExp - e0
284 in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
290 (f*be*b*2, 2*b, be*b, b)
294 if e > minExp && f == b^(p-1) then
295 (f*b*2, b^(-e+1)*2, b, 1)
297 (f*2, b^(-e)*2, 1, 1)
300 if b==2 && base==10 then
301 -- logBase 10 2 is slightly bigger than 3/10 so
302 -- the following will err on the low side. Ignoring
303 -- the fraction will make it err even more.
304 -- Haskell promises that p-1 <= logBase b f < p.
305 (p - 1 + e0) * 3 `div` 10
307 ceiling ((log (fromInteger (f+1)) +
308 fromIntegral e * log (fromInteger b)) /
309 log (fromInteger base))
312 if r + mUp <= expt base n * s then n else fixup (n+1)
314 if expt base (-n) * (r + mUp) <= s then n
318 gen ds rn sN mUpN mDnN =
319 let (dn, rn') = (rn * base) `divMod` sN
322 in case (rn' < mDnN', rn' + mUpN' > sN) of
323 (True, False) -> dn : ds
324 (False, True) -> dn+1 : ds
325 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
326 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
329 gen [] r (s * expt base k) mUp mDn
331 let bk = expt base (-k)
332 in gen [] (r * bk) s (mUp * bk) (mDn * bk)
333 in (map fromIntegral (reverse rds), k)
336 -- ---------------------------------------------------------------------------
337 -- Integer printing functions
339 showIntAtBase :: Integral a => a -> (a -> Char) -> a -> ShowS
340 showIntAtBase base toChr n r
341 | n < 0 = error ("Numeric.showIntAtBase: applied to negative number " ++ show n)
343 case quotRem n base of { (n', d) ->
345 seq c $ -- stricter than necessary
349 if n' == 0 then r' else showIntAtBase base toChr n' r'
352 showHex :: Integral a => a -> ShowS
355 showIntAtBase 16 (toChrHex) n r
358 | d < 10 = chr (ord '0' + fromIntegral d)
359 | otherwise = chr (ord 'a' + fromIntegral (d - 10))
361 showOct :: Integral a => a -> ShowS
364 showIntAtBase 8 (toChrOct) n r
365 where toChrOct d = chr (ord '0' + fromIntegral d)
367 showBin :: Integral a => a -> ShowS
370 showIntAtBase 2 (toChrOct) n r
371 where toChrOct d = chr (ord '0' + fromIntegral d)