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