[project @ 1999-10-29 01:16:48 by andy]
[ghc-hetmet.git] / ghc / lib / std / Numeric.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1997-99
3 %
4 \section[Numeric]{Numeric interface}
5
6 Odds and ends, mostly functions for reading and showing
7 \tr{RealFloat}-like kind of values.
8
9
10 \begin{code}
11 {-# OPTIONS -fno-implicit-prelude #-}
12 module Numeric
13
14         ( fromRat          -- :: (RealFloat a) => Rational -> a
15         , showSigned       -- :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS
16         , readSigned       -- :: (Real a) => ReadS a -> ReadS a
17         , showInt          -- :: Integral a => a -> ShowS
18         , readInt          -- :: (Integral a) => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
19         
20         , readDec          -- :: (Integral a) => ReadS a
21         , readOct          -- :: (Integral a) => ReadS a
22         , readHex          -- :: (Integral a) => ReadS a
23
24         , showEFloat       -- :: (RealFloat a) => Maybe Int -> a -> ShowS
25         , showFFloat       -- :: (RealFloat a) => Maybe Int -> a -> ShowS
26         , showGFloat       -- :: (RealFloat a) => Maybe Int -> a -> ShowS
27         , showFloat        -- :: (RealFloat a) => a -> ShowS
28         , readFloat        -- :: (RealFloat a) => ReadS a
29         
30          
31         , floatToDigits    -- :: (RealFloat a) => Integer -> a -> ([Int], Int)
32         , lexDigits        -- :: ReadS String
33
34           -- Implementation checked wrt. Haskell 98 lib report, 1/99.
35         ) where
36
37 #ifndef __HUGS__
38 import PrelBase
39 import PrelMaybe
40 import PrelShow
41 import PrelArr
42 import PrelNum
43 import PrelNumExtra
44 import PrelRead
45 import PrelErr ( error )
46 #else
47 import Char
48 import Array
49 #endif
50 \end{code}
51
52 #ifndef __HUGS__
53
54 \begin{code}
55 showInt :: Integral a => a -> ShowS
56 showInt i rs
57   | i < 0     = error "Numeric.showInt: can't show negative numbers"
58   | otherwise = go i rs
59     where
60      go n r = 
61       case quotRem n 10 of                 { (n', d) ->
62       case chr (ord_0 + fromIntegral d) of { C# c# -> -- stricter than necessary
63       let
64         r' = C# c# : r
65       in
66       if n' == 0 then r' else go n' r'
67       }}
68 \end{code}
69
70 Controlling the format and precision of floats. The code that
71 implements the formatting itself is in @PrelNum@ to avoid
72 mutual module deps.
73
74 \begin{code}
75 showEFloat    :: (RealFloat a) => Maybe Int -> a -> ShowS
76 showFFloat    :: (RealFloat a) => Maybe Int -> a -> ShowS
77 showGFloat    :: (RealFloat a) => Maybe Int -> a -> ShowS
78
79 showEFloat d x =  showString (formatRealFloat FFExponent d x)
80 showFFloat d x =  showString (formatRealFloat FFFixed d x)
81 showGFloat d x =  showString (formatRealFloat FFGeneric d x)
82
83 \end{code}
84
85 #else
86 \begin{code}
87 -- This converts a rational to a floating.  This should be used in the
88 -- Fractional instances of Float and Double.
89
90 fromRat :: (RealFloat a) => Rational -> a
91 fromRat x = 
92     if x == 0 then encodeFloat 0 0              -- Handle exceptional cases
93     else if x < 0 then - fromRat' (-x)          -- first.
94     else fromRat' x
95
96 -- Conversion process:
97 -- Scale the rational number by the RealFloat base until
98 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
99 -- Then round the rational to an Integer and encode it with the exponent
100 -- that we got from the scaling.
101 -- To speed up the scaling process we compute the log2 of the number to get
102 -- a first guess of the exponent.
103 fromRat' :: (RealFloat a) => Rational -> a
104 fromRat' x = r
105   where b = floatRadix r
106         p = floatDigits r
107         (minExp0, _) = floatRange r
108         minExp = minExp0 - p            -- the real minimum exponent
109         xMin = toRational (expt b (p-1))
110         xMax = toRational (expt b p)
111         p0 = (integerLogBase b (numerator x) -
112               integerLogBase b (denominator x) - p) `max` minExp
113         f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
114         (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
115         r = encodeFloat (round x') p'
116
117 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
118 scaleRat :: Rational -> Int -> Rational -> Rational -> 
119              Int -> Rational -> (Rational, Int)
120 scaleRat b minExp xMin xMax p x =
121     if p <= minExp then
122         (x, p)
123     else if x >= xMax then
124         scaleRat b minExp xMin xMax (p+1) (x/b)
125     else if x < xMin  then
126         scaleRat b minExp xMin xMax (p-1) (x*b)
127     else
128         (x, p)
129
130 -- Exponentiation with a cache for the most common numbers.
131 minExpt = 0::Int
132 maxExpt = 1100::Int
133 expt :: Integer -> Int -> Integer
134 expt base n =
135     if base == 2 && n >= minExpt && n <= maxExpt then
136         expts!n
137     else
138         base^n
139
140 expts :: Array Int Integer
141 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
142
143 -- Compute the (floor of the) log of i in base b.
144 -- Simplest way would be just divide i by b until it's smaller then b,
145 -- but that would be very slow!  We are just slightly more clever.
146 integerLogBase :: Integer -> Integer -> Int
147 integerLogBase b i =
148      if i < b then
149         0
150      else
151         -- Try squaring the base first to cut down the number of divisions.
152         let l = 2 * integerLogBase (b*b) i
153             doDiv :: Integer -> Int -> Int
154             doDiv i l = if i < b then l else doDiv (i `div` b) (l+1)
155         in  doDiv (i `div` (b^l)) l
156
157
158 -- Misc utilities to show integers and floats 
159
160 showEFloat     :: (RealFloat a) => Maybe Int -> a -> ShowS
161 showFFloat     :: (RealFloat a) => Maybe Int -> a -> ShowS
162 showGFloat     :: (RealFloat a) => Maybe Int -> a -> ShowS
163 showFloat      :: (RealFloat a) => a -> ShowS
164
165 showEFloat d x =  showString (formatRealFloat FFExponent d x)
166 showFFloat d x =  showString (formatRealFloat FFFixed d x)
167 showGFloat d x =  showString (formatRealFloat FFGeneric d x)
168 showFloat      =  showGFloat Nothing 
169
170 -- These are the format types.  This type is not exported.
171
172 data FFFormat = FFExponent | FFFixed | FFGeneric
173
174 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
175 formatRealFloat fmt decs x = s
176   where base = 10
177         s = if isNaN x then 
178                 "NaN"
179             else if isInfinite x then 
180                 if x < 0 then "-Infinity" else "Infinity"
181             else if x < 0 || isNegativeZero x then 
182                 '-' : doFmt fmt (floatToDigits (toInteger base) (-x))
183             else 
184                 doFmt fmt (floatToDigits (toInteger base) x)
185         doFmt fmt (is, e) =
186             let ds = map intToDigit is
187             in  case fmt of
188                 FFGeneric -> 
189                     doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
190                           (is, e)
191                 FFExponent ->
192                     case decs of
193                     Nothing ->
194                         case ds of
195                          ['0'] -> "0.0e0"
196                          [d]   -> d : ".0e" ++ show (e-1)
197                          d:ds  -> d : '.' : ds ++ 'e':show (e-1)
198                     Just dec ->
199                         let dec' = max dec 1 in
200                         case is of
201                          [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
202                          _ ->
203                           let (ei, is') = roundTo base (dec'+1) is
204                               d:ds = map intToDigit
205                                          (if ei > 0 then init is' else is')
206                           in d:'.':ds  ++ "e" ++ show (e-1+ei)
207                 FFFixed ->
208                     case decs of
209                     Nothing ->
210                         let f 0 s ds = mk0 s ++ "." ++ mk0 ds
211                             f n s "" = f (n-1) (s++"0") ""
212                             f n s (d:ds) = f (n-1) (s++[d]) ds
213                             mk0 "" = "0"
214                             mk0 s = s
215                         in  f e "" ds
216                     Just dec ->
217                         let dec' = max dec 0 in
218                         if e >= 0 then
219                             let (ei, is') = roundTo base (dec' + e) is
220                                 (ls, rs) = splitAt (e+ei) (map intToDigit is')
221                             in  (if null ls then "0" else ls) ++ 
222                                 (if null rs then "" else '.' : rs)
223                         else
224                             let (ei, is') = roundTo base dec'
225                                               (replicate (-e) 0 ++ is)
226                                 d : ds = map intToDigit
227                                             (if ei > 0 then is' else 0:is')
228                             in  d : '.' : ds
229
230 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
231 roundTo base d is = case f d is of
232                 (0, is) -> (0, is)
233                 (1, is) -> (1, 1 : is)
234   where b2 = base `div` 2
235         f n [] = (0, replicate n 0)
236         f 0 (i:_) = (if i >= b2 then 1 else 0, [])
237         f d (i:is) = 
238             let (c, ds) = f (d-1) is
239                 i' = c + i
240             in  if i' == base then (1, 0:ds) else (0, i':ds)
241
242 --
243 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
244 -- by R.G. Burger and R. K. Dybvig, in PLDI 96.
245 -- This version uses a much slower logarithm estimator.  It should be improved.
246
247 -- This function returns a list of digits (Ints in [0..base-1]) and an
248 -- exponent.
249
250 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
251
252 floatToDigits _ 0 = ([0], 0)
253 floatToDigits base x =
254     let (f0, e0) = decodeFloat x
255         (minExp0, _) = floatRange x
256         p = floatDigits x
257         b = floatRadix x
258         minExp = minExp0 - p            -- the real minimum exponent
259         -- Haskell requires that f be adjusted so denormalized numbers
260         -- will have an impossibly low exponent.  Adjust for this.
261         (f, e) = let n = minExp - e0
262                  in  if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
263
264         (r, s, mUp, mDn) =
265            if e >= 0 then
266                let be = b^e in
267                if f == b^(p-1) then
268                    (f*be*b*2, 2*b, be*b, b)
269                else
270                    (f*be*2, 2, be, be)
271            else
272                if e > minExp && f == b^(p-1) then
273                    (f*b*2, b^(-e+1)*2, b, 1)
274                else
275                    (f*2, b^(-e)*2, 1, 1)
276         k = 
277             let k0 =
278                     if b==2 && base==10 then
279                         -- logBase 10 2 is slightly bigger than 3/10 so
280                         -- the following will err on the low side.  Ignoring
281                         -- the fraction will make it err even more.
282                         -- Haskell promises that p-1 <= logBase b f < p.
283                         (p - 1 + e0) * 3 `div` 10
284                     else
285                         ceiling ((log (fromInteger (f+1)) + 
286                                  fromInt e * log (fromInteger b)) / 
287                                   log (fromInteger base))
288                 fixup n =
289                     if n >= 0 then
290                         if r + mUp <= expt base n * s then n else fixup (n+1)
291                     else
292                         if expt base (-n) * (r + mUp) <= s then n
293                                                            else fixup (n+1)
294             in  fixup k0
295
296         gen ds rn sN mUpN mDnN =
297             let (dn, rn') = (rn * base) `divMod` sN
298                 mUpN' = mUpN * base
299                 mDnN' = mDnN * base
300             in  case (rn' < mDnN', rn' + mUpN' > sN) of
301                 (True,  False) -> dn : ds
302                 (False, True)  -> dn+1 : ds
303                 (True,  True)  -> if rn' * 2 < sN then dn : ds else dn+1 : ds
304                 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
305         rds =
306             if k >= 0 then
307                 gen [] r (s * expt base k) mUp mDn
308             else
309                 let bk = expt base (-k)
310                 in  gen [] (r * bk) s (mUp * bk) (mDn * bk)
311     in  (map toInt (reverse rds), k)
312 \end{code}
313 #endif