[project @ 2002-05-15 12:16:11 by simonmar]
[packages/base.git] / Numeric.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module : Numeric
5 -- Copyright : (c) The University of Glasgow 2002
6 -- License : BSD-style (see the file libraries/base/LICENSE)
7 --
8 -- Maintainer : libraries@haskell.org
9 -- Stability : provisional
10 -- Portability : portable
11 --
12 -- Odds and ends, mostly functions for reading and showing
13 -- RealFloat-like kind of values.
14 --
15 -----------------------------------------------------------------------------
16
17 module Numeric (
18
19 fromRat, -- :: (RealFloat a) => Rational -> a
20 showSigned, -- :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS
21 readSigned, -- :: (Real a) => ReadS a -> ReadS a
22
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
28
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
34
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
40
41 floatToDigits, -- :: (RealFloat a) => Integer -> a -> ([Int], Int)
42 lexDigits, -- :: ReadS String
43
44 ) where
45
46 import Data.Char
47
48 #ifdef __GLASGOW_HASKELL__
49 import GHC.Base
50 import GHC.Read
51 import GHC.Real
52 import GHC.Float
53 import GHC.Num
54 import GHC.Show
55 import Data.Maybe
56 import Text.ParserCombinators.ReadP( ReadP, readP_to_S, pfail )
57 import qualified Text.Read.Lex as L
58 #endif
59
60 #ifdef __HUGS__
61 import Array
62 #endif
63
64
65 -- -----------------------------------------------------------------------------
66 -- Reading
67
68 readInt :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
69 readInt base isDigit valDigit = readP_to_S (L.readIntP base isDigit valDigit)
70
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
75
76 readFloat :: RealFrac a => ReadS a
77 readFloat = readP_to_S readFloatP
78
79 readFloatP :: RealFrac a => ReadP a
80 readFloatP =
81 do L.Number x <- L.lex
82 case L.numberToRational x of
83 Nothing -> pfail
84 Just y -> return (fromRational y)
85
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 ++
92 (do
93 ("-",s) <- lex r
94 (x,t) <- read'' s
95 return (-x,t))
96 read'' r = do
97 (str,s) <- lex r
98 (n,"") <- readPos str
99 return (n,s)
100
101
102 -- -----------------------------------------------------------------------------
103 -- Showing
104
105 #ifdef __GLASGOW_HASKELL__
106 showInt :: Integral a => a -> ShowS
107 showInt n cs
108 | n < 0 = error "Numeric.showInt: can't show negative numbers"
109 | otherwise = go n cs
110 where
111 go n cs
112 | n < 10 = case unsafeChr (ord '0' + fromIntegral n) of
113 c@(C# _) -> c:cs
114 | otherwise = case unsafeChr (ord '0' + fromIntegral r) of
115 c@(C# _) -> go q (c:cs)
116 where
117 (q,r) = n `quotRem` 10
118
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.
122
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 #-}
132
133 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
134 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
135 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
136
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)
140 #endif
141
142 #ifdef __HUGS__
143 -- This converts a rational to a floating. This should be used in the
144 -- Fractional instances of Float and Double.
145
146 fromRat :: (RealFloat a) => Rational -> a
147 fromRat x =
148 if x == 0 then encodeFloat 0 0 -- Handle exceptional cases
149 else if x < 0 then - fromRat' (-x) -- first.
150 else fromRat' x
151
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
160 fromRat' x = r
161 where b = floatRadix r
162 p = floatDigits 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'
172
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 =
177 if p <= minExp then
178 (x, p)
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)
183 else
184 (x, p)
185
186 -- Exponentiation with a cache for the most common numbers.
187 minExpt = 0::Int
188 maxExpt = 1100::Int
189 expt :: Integer -> Int -> Integer
190 expt base n =
191 if base == 2 && n >= minExpt && n <= maxExpt then
192 expts!n
193 else
194 base^n
195
196 expts :: Array Int Integer
197 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
198
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
203 integerLogBase b i =
204 if i < b then
205 0
206 else
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
212
213
214 -- Misc utilities to show integers and floats
215
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
220
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
225
226 -- These are the format types. This type is not exported.
227
228 data FFFormat = FFExponent | FFFixed | FFGeneric
229
230 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
231 formatRealFloat fmt decs x = s
232 where base = 10
233 s = if isNaN x then
234 "NaN"
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))
239 else
240 doFmt fmt (floatToDigits (toInteger base) x)
241 doFmt fmt (is, e) =
242 let ds = map intToDigit is
243 in case fmt of
244 FFGeneric ->
245 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
246 (is, e)
247 FFExponent ->
248 case decs of
249 Nothing ->
250 case ds of
251 ['0'] -> "0.0e0"
252 [d] -> d : ".0e" ++ show (e-1)
253 d:ds -> d : '.' : ds ++ 'e':show (e-1)
254 Just dec ->
255 let dec' = max dec 1 in
256 case is of
257 [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
258 _ ->
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)
263 FFFixed ->
264 case decs of
265 Nothing ->
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
269 mk0 "" = "0"
270 mk0 s = s
271 in f e "" ds
272 Just dec ->
273 let dec' = max dec 0 in
274 if e >= 0 then
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)
279 else
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')
284 in d : '.' : ds
285
286 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
287 roundTo base d is = case f d is of
288 (0, is) -> (0, is)
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, [])
293 f d (i:is) =
294 let (c, ds) = f (d-1) is
295 i' = c + i
296 in if i' == base then (1, 0:ds) else (0, i':ds)
297
298 --
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.
302
303 -- This function returns a list of digits (Ints in [0..base-1]) and an
304 -- exponent.
305
306 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
307
308 floatToDigits _ 0 = ([0], 0)
309 floatToDigits base x =
310 let (f0, e0) = decodeFloat x
311 (minExp0, _) = floatRange x
312 p = floatDigits x
313 b = floatRadix 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)
319
320 (r, s, mUp, mDn) =
321 if e >= 0 then
322 let be = b^e in
323 if f == b^(p-1) then
324 (f*be*b*2, 2*b, be*b, b)
325 else
326 (f*be*2, 2, be, be)
327 else
328 if e > minExp && f == b^(p-1) then
329 (f*b*2, b^(-e+1)*2, b, 1)
330 else
331 (f*2, b^(-e)*2, 1, 1)
332 k =
333 let k0 =
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
340 else
341 ceiling ((log (fromInteger (f+1)) +
342 fromIntegral e * log (fromInteger b)) /
343 log (fromInteger base))
344 fixup n =
345 if n >= 0 then
346 if r + mUp <= expt base n * s then n else fixup (n+1)
347 else
348 if expt base (-n) * (r + mUp) <= s then n
349 else fixup (n+1)
350 in fixup k0
351
352 gen ds rn sN mUpN mDnN =
353 let (dn, rn') = (rn * base) `divMod` sN
354 mUpN' = mUpN * base
355 mDnN' = mDnN * base
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'
361 rds =
362 if k >= 0 then
363 gen [] r (s * expt base k) mUp mDn
364 else
365 let bk = expt base (-k)
366 in gen [] (r * bk) s (mUp * bk) (mDn * bk)
367 in (map fromIntegral (reverse rds), k)
368 #endif
369
370 -- ---------------------------------------------------------------------------
371 -- Integer printing functions
372
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)
376 | otherwise =
377 case quotRem n base of { (n', d) ->
378 let c = toChr d in
379 seq c $ -- stricter than necessary
380 let
381 r' = c : r
382 in
383 if n' == 0 then r' else showIntAtBase base toChr n' r'
384 }
385
386 showHex :: Integral a => a -> ShowS
387 showHex n r =
388 showString "0x" $
389 showIntAtBase 16 (toChrHex) n r
390 where
391 toChrHex d
392 | d < 10 = chr (ord '0' + fromIntegral d)
393 | otherwise = chr (ord 'a' + fromIntegral (d - 10))
394
395 showOct :: Integral a => a -> ShowS
396 showOct n r =
397 showString "0o" $
398 showIntAtBase 8 (toChrOct) n r
399 where toChrOct d = chr (ord '0' + fromIntegral d)
400
401 showBin :: Integral a => a -> ShowS
402 showBin n r =
403 showString "0b" $
404 showIntAtBase 2 (toChrOct) n r
405 where toChrOct d = chr (ord '0' + fromIntegral d)