1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
5 -- Copyright : (c) The University of Glasgow 2002
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : provisional
10 -- Portability : portable
12 -- Odds and ends, mostly functions for reading and showing
13 -- RealFloat-like kind of values.
15 -----------------------------------------------------------------------------
19 fromRat, -- :: (RealFloat a) => Rational -> a
20 showSigned, -- :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS
21 readSigned, -- :: (Real a) => ReadS a -> ReadS a
23 readInt, -- :: (Integral a) => a -> (Char -> Bool)
24 -- -> (Char -> Int) -> ReadS a
25 readDec, -- :: (Integral a) => ReadS a
26 readOct, -- :: (Integral a) => ReadS a
27 readHex, -- :: (Integral a) => ReadS a
29 showInt, -- :: Integral a => a -> ShowS
30 showIntAtBase, -- :: Integral a => a -> (a -> Char) -> a -> ShowS
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
41 floatToDigits, -- :: (RealFloat a) => Integer -> a -> ([Int], Int)
42 lexDigits, -- :: ReadS String
48 #ifdef __GLASGOW_HASKELL__
56 import Text.ParserCombinators.ReadP( ReadP, readP_to_S, pfail )
57 import qualified Text.Read.Lex as L
65 -- -----------------------------------------------------------------------------
68 readInt :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
69 readInt base isDigit valDigit = readP_to_S (L.readIntP base isDigit valDigit)
71 readOct, readDec, readHex :: Num a => ReadS a
72 readOct = readP_to_S L.readOctP
73 readDec = readP_to_S L.readDecP
74 readHex = readP_to_S L.readHexP
76 readFloat :: RealFrac a => ReadS a
77 readFloat = readP_to_S readFloatP
79 readFloatP :: RealFrac a => ReadP a
81 do L.Number x <- L.lex
82 case L.numberToRational x of
84 Just y -> return (fromRational y)
86 -- It's turgid to have readSigned work using list comprehensions,
87 -- but it's specified as a ReadS to ReadS transformer
88 -- With a bit of luck no one will use it.
89 readSigned :: (Real a) => ReadS a -> ReadS a
90 readSigned readPos = readParen False read'
91 where read' r = read'' r ++
102 -- -----------------------------------------------------------------------------
105 #ifdef __GLASGOW_HASKELL__
106 showInt :: Integral a => a -> ShowS
108 | n < 0 = error "Numeric.showInt: can't show negative numbers"
109 | otherwise = go n cs
112 | n < 10 = case unsafeChr (ord '0' + fromIntegral n) of
114 | otherwise = case unsafeChr (ord '0' + fromIntegral r) of
115 c@(C# _) -> go q (c:cs)
117 (q,r) = n `quotRem` 10
119 -- Controlling the format and precision of floats. The code that
120 -- implements the formatting itself is in @PrelNum@ to avoid
121 -- mutual module deps.
123 {-# SPECIALIZE showEFloat ::
124 Maybe Int -> Float -> ShowS,
125 Maybe Int -> Double -> ShowS #-}
126 {-# SPECIALIZE showFFloat ::
127 Maybe Int -> Float -> ShowS,
128 Maybe Int -> Double -> ShowS #-}
129 {-# SPECIALIZE showGFloat ::
130 Maybe Int -> Float -> ShowS,
131 Maybe Int -> Double -> ShowS #-}
133 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
134 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
135 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
137 showEFloat d x = showString (formatRealFloat FFExponent d x)
138 showFFloat d x = showString (formatRealFloat FFFixed d x)
139 showGFloat d x = showString (formatRealFloat FFGeneric d x)
143 -- This converts a rational to a floating. This should be used in the
144 -- Fractional instances of Float and Double.
146 fromRat :: (RealFloat a) => Rational -> a
148 if x == 0 then encodeFloat 0 0 -- Handle exceptional cases
149 else if x < 0 then - fromRat' (-x) -- first.
152 -- Conversion process:
153 -- Scale the rational number by the RealFloat base until
154 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
155 -- Then round the rational to an Integer and encode it with the exponent
156 -- that we got from the scaling.
157 -- To speed up the scaling process we compute the log2 of the number to get
158 -- a first guess of the exponent.
159 fromRat' :: (RealFloat a) => Rational -> a
161 where b = floatRadix r
163 (minExp0, _) = floatRange r
164 minExp = minExp0 - p -- the real minimum exponent
165 xMin = toRational (expt b (p-1))
166 xMax = toRational (expt b p)
167 p0 = (integerLogBase b (numerator x) -
168 integerLogBase b (denominator x) - p) `max` minExp
169 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
170 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
171 r = encodeFloat (round x') p'
173 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
174 scaleRat :: Rational -> Int -> Rational -> Rational ->
175 Int -> Rational -> (Rational, Int)
176 scaleRat b minExp xMin xMax p x =
179 else if x >= xMax then
180 scaleRat b minExp xMin xMax (p+1) (x/b)
181 else if x < xMin then
182 scaleRat b minExp xMin xMax (p-1) (x*b)
186 -- Exponentiation with a cache for the most common numbers.
189 expt :: Integer -> Int -> Integer
191 if base == 2 && n >= minExpt && n <= maxExpt then
196 expts :: Array Int Integer
197 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
199 -- Compute the (floor of the) log of i in base b.
200 -- Simplest way would be just divide i by b until it's smaller then b,
201 -- but that would be very slow! We are just slightly more clever.
202 integerLogBase :: Integer -> Integer -> Int
207 -- Try squaring the base first to cut down the number of divisions.
208 let l = 2 * integerLogBase (b*b) i
209 doDiv :: Integer -> Int -> Int
210 doDiv i l = if i < b then l else doDiv (i `div` b) (l+1)
211 in doDiv (i `div` (b^l)) l
214 -- Misc utilities to show integers and floats
216 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
217 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
218 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
219 showFloat :: (RealFloat a) => a -> ShowS
221 showEFloat d x = showString (formatRealFloat FFExponent d x)
222 showFFloat d x = showString (formatRealFloat FFFixed d x)
223 showGFloat d x = showString (formatRealFloat FFGeneric d x)
224 showFloat = showGFloat Nothing
226 -- These are the format types. This type is not exported.
228 data FFFormat = FFExponent | FFFixed | FFGeneric
230 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
231 formatRealFloat fmt decs x = s
235 else if isInfinite x then
236 if x < 0 then "-Infinity" else "Infinity"
237 else if x < 0 || isNegativeZero x then
238 '-' : doFmt fmt (floatToDigits (toInteger base) (-x))
240 doFmt fmt (floatToDigits (toInteger base) x)
242 let ds = map intToDigit is
245 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
252 [d] -> d : ".0e" ++ show (e-1)
253 d:ds -> d : '.' : ds ++ 'e':show (e-1)
255 let dec' = max dec 1 in
257 [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
259 let (ei, is') = roundTo base (dec'+1) is
260 d:ds = map intToDigit
261 (if ei > 0 then init is' else is')
262 in d:'.':ds ++ "e" ++ show (e-1+ei)
266 let f 0 s ds = mk0 s ++ "." ++ mk0 ds
267 f n s "" = f (n-1) (s++"0") ""
268 f n s (d:ds) = f (n-1) (s++[d]) ds
273 let dec' = max dec 0 in
275 let (ei, is') = roundTo base (dec' + e) is
276 (ls, rs) = splitAt (e+ei) (map intToDigit is')
277 in (if null ls then "0" else ls) ++
278 (if null rs then "" else '.' : rs)
280 let (ei, is') = roundTo base dec'
281 (replicate (-e) 0 ++ is)
282 d : ds = map intToDigit
283 (if ei > 0 then is' else 0:is')
286 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
287 roundTo base d is = case f d is of
289 (1, is) -> (1, 1 : is)
290 where b2 = base `div` 2
291 f n [] = (0, replicate n 0)
292 f 0 (i:_) = (if i >= b2 then 1 else 0, [])
294 let (c, ds) = f (d-1) is
296 in if i' == base then (1, 0:ds) else (0, i':ds)
299 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
300 -- by R.G. Burger and R. K. Dybvig, in PLDI 96.
301 -- This version uses a much slower logarithm estimator. It should be improved.
303 -- This function returns a list of digits (Ints in [0..base-1]) and an
306 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
308 floatToDigits _ 0 = ([0], 0)
309 floatToDigits base x =
310 let (f0, e0) = decodeFloat x
311 (minExp0, _) = floatRange x
314 minExp = minExp0 - p -- the real minimum exponent
315 -- Haskell requires that f be adjusted so denormalized numbers
316 -- will have an impossibly low exponent. Adjust for this.
317 (f, e) = let n = minExp - e0
318 in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
324 (f*be*b*2, 2*b, be*b, b)
328 if e > minExp && f == b^(p-1) then
329 (f*b*2, b^(-e+1)*2, b, 1)
331 (f*2, b^(-e)*2, 1, 1)
334 if b==2 && base==10 then
335 -- logBase 10 2 is slightly bigger than 3/10 so
336 -- the following will err on the low side. Ignoring
337 -- the fraction will make it err even more.
338 -- Haskell promises that p-1 <= logBase b f < p.
339 (p - 1 + e0) * 3 `div` 10
341 ceiling ((log (fromInteger (f+1)) +
342 fromIntegral e * log (fromInteger b)) /
343 log (fromInteger base))
346 if r + mUp <= expt base n * s then n else fixup (n+1)
348 if expt base (-n) * (r + mUp) <= s then n
352 gen ds rn sN mUpN mDnN =
353 let (dn, rn') = (rn * base) `divMod` sN
356 in case (rn' < mDnN', rn' + mUpN' > sN) of
357 (True, False) -> dn : ds
358 (False, True) -> dn+1 : ds
359 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
360 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
363 gen [] r (s * expt base k) mUp mDn
365 let bk = expt base (-k)
366 in gen [] (r * bk) s (mUp * bk) (mDn * bk)
367 in (map fromIntegral (reverse rds), k)
370 -- ---------------------------------------------------------------------------
371 -- Integer printing functions
373 showIntAtBase :: Integral a => a -> (a -> Char) -> a -> ShowS
374 showIntAtBase base toChr n r
375 | n < 0 = error ("Numeric.showIntAtBase: applied to negative number " ++ show n)
377 case quotRem n base of { (n', d) ->
379 seq c $ -- stricter than necessary
383 if n' == 0 then r' else showIntAtBase base toChr n' r'
386 showHex :: Integral a => a -> ShowS
389 showIntAtBase 16 (toChrHex) n r
392 | d < 10 = chr (ord '0' + fromIntegral d)
393 | otherwise = chr (ord 'a' + fromIntegral (d - 10))
395 showOct :: Integral a => a -> ShowS
398 showIntAtBase 8 (toChrOct) n r
399 where toChrOct d = chr (ord '0' + fromIntegral d)
401 showBin :: Integral a => a -> ShowS
404 showIntAtBase 2 (toChrOct) n r
405 where toChrOct d = chr (ord '0' + fromIntegral d)