[project @ 2005-02-03 10:32:11 by ross]
[ghc-base.git] / GHC / Float.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.Float
6 -- Copyright   :  (c) The University of Glasgow 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- The types 'Float' and 'Double', and the classes 'Floating' and 'RealFloat'.
14 --
15 -----------------------------------------------------------------------------
16
17 #include "ieee-flpt.h"
18
19 -- #hide
20 module GHC.Float( module GHC.Float, Float#, Double# )  where
21
22 import Data.Maybe
23
24 import GHC.Base
25 import GHC.List
26 import GHC.Enum
27 import GHC.Show
28 import GHC.Num
29 import GHC.Real
30 import GHC.Arr
31
32 infixr 8  **
33 \end{code}
34
35 %*********************************************************
36 %*                                                      *
37 \subsection{Standard numeric classes}
38 %*                                                      *
39 %*********************************************************
40
41 \begin{code}
42 -- | Trigonometric and hyperbolic functions and related functions.
43 --
44 -- Minimal complete definition:
45 --      'pi', 'exp', 'log', 'sin', 'cos', 'sinh', 'cosh'
46 --      'asin', 'acos', 'atan', 'asinh', 'acosh' and 'atanh'
47 class  (Fractional a) => Floating a  where
48     pi                  :: a
49     exp, log, sqrt      :: a -> a
50     (**), logBase       :: a -> a -> a
51     sin, cos, tan       :: a -> a
52     asin, acos, atan    :: a -> a
53     sinh, cosh, tanh    :: a -> a
54     asinh, acosh, atanh :: a -> a
55
56     x ** y              =  exp (log x * y)
57     logBase x y         =  log y / log x
58     sqrt x              =  x ** 0.5
59     tan  x              =  sin  x / cos  x
60     tanh x              =  sinh x / cosh x
61
62 -- | Efficient, machine-independent access to the components of a
63 -- floating-point number.
64 --
65 -- Minimal complete definition:
66 --      all except 'exponent', 'significand', 'scaleFloat' and 'atan2'
67 class  (RealFrac a, Floating a) => RealFloat a  where
68     -- | a constant function, returning the radix of the representation
69     -- (often @2@)
70     floatRadix          :: a -> Integer
71     -- | a constant function, returning the number of digits of
72     -- 'floatRadix' in the significand
73     floatDigits         :: a -> Int
74     -- | a constant function, returning the lowest and highest values
75     -- the exponent may assume
76     floatRange          :: a -> (Int,Int)
77     -- | The function 'decodeFloat' applied to a real floating-point
78     -- number returns the significand expressed as an 'Integer' and an
79     -- appropriately scaled exponent (an 'Int').  If @'decodeFloat' x@
80     -- yields @(m,n)@, then @x@ is equal in value to @m*b^^n@, where @b@
81     -- is the floating-point radix, and furthermore, either @m@ and @n@
82     -- are both zero or else @b^(d-1) <= m < b^d@, where @d@ is the value
83     -- of @'floatDigits' x@.  In particular, @'decodeFloat' 0 = (0,0)@.
84     decodeFloat         :: a -> (Integer,Int)
85     -- | 'encodeFloat' performs the inverse of 'decodeFloat'
86     encodeFloat         :: Integer -> Int -> a
87     -- | the second component of 'decodeFloat'.
88     exponent            :: a -> Int
89     -- | the first component of 'decodeFloat', scaled to lie in the open
90     -- interval (@-1@,@1@)
91     significand         :: a -> a
92     -- | multiplies a floating-point number by an integer power of the radix
93     scaleFloat          :: Int -> a -> a
94     -- | 'True' if the argument is an IEEE \"not-a-number\" (NaN) value
95     isNaN               :: a -> Bool
96     -- | 'True' if the argument is an IEEE infinity or negative infinity
97     isInfinite          :: a -> Bool
98     -- | 'True' if the argument is too small to be represented in
99     -- normalized format
100     isDenormalized      :: a -> Bool
101     -- | 'True' if the argument is an IEEE negative zero
102     isNegativeZero      :: a -> Bool
103     -- | 'True' if the argument is an IEEE floating point number
104     isIEEE              :: a -> Bool
105     -- | a version of arctangent taking two real floating-point arguments.
106     -- For real floating @x@ and @y@, @'atan2' y x@ computes the angle
107     -- (from the positive x-axis) of the vector from the origin to the
108     -- point @(x,y)@.  @'atan2' y x@ returns a value in the range [@-pi@,
109     -- @pi@].  It follows the Common Lisp semantics for the origin when
110     -- signed zeroes are supported.  @'atan2' y 1@, with @y@ in a type
111     -- that is 'RealFloat', should return the same value as @'atan' y@.
112     -- A default definition of 'atan2' is provided, but implementors
113     -- can provide a more accurate implementation.
114     atan2               :: a -> a -> a
115
116
117     exponent x          =  if m == 0 then 0 else n + floatDigits x
118                            where (m,n) = decodeFloat x
119
120     significand x       =  encodeFloat m (negate (floatDigits x))
121                            where (m,_) = decodeFloat x
122
123     scaleFloat k x      =  encodeFloat m (n+k)
124                            where (m,n) = decodeFloat x
125                            
126     atan2 y x
127       | x > 0            =  atan (y/x)
128       | x == 0 && y > 0  =  pi/2
129       | x <  0 && y > 0  =  pi + atan (y/x) 
130       |(x <= 0 && y < 0)            ||
131        (x <  0 && isNegativeZero y) ||
132        (isNegativeZero x && isNegativeZero y)
133                          = -atan2 (-y) x
134       | y == 0 && (x < 0 || isNegativeZero x)
135                           =  pi    -- must be after the previous test on zero y
136       | x==0 && y==0      =  y     -- must be after the other double zero tests
137       | otherwise         =  x + y -- x or y is a NaN, return a NaN (via +)
138 \end{code}
139
140
141 %*********************************************************
142 %*                                                      *
143 \subsection{Type @Integer@, @Float@, @Double@}
144 %*                                                      *
145 %*********************************************************
146
147 \begin{code}
148 -- | Single-precision floating point numbers.
149 -- It is desirable that this type be at least equal in range and precision
150 -- to the IEEE single-precision type.
151 data Float      = F# Float#
152
153 -- | Double-precision floating point numbers.
154 -- It is desirable that this type be at least equal in range and precision
155 -- to the IEEE double-precision type.
156 data Double     = D# Double#
157 \end{code}
158
159
160 %*********************************************************
161 %*                                                      *
162 \subsection{Type @Float@}
163 %*                                                      *
164 %*********************************************************
165
166 \begin{code}
167 instance Eq Float where
168     (F# x) == (F# y) = x `eqFloat#` y
169
170 instance Ord Float where
171     (F# x) `compare` (F# y) | x `ltFloat#` y = LT
172                             | x `eqFloat#` y = EQ
173                             | otherwise      = GT
174
175     (F# x) <  (F# y) = x `ltFloat#`  y
176     (F# x) <= (F# y) = x `leFloat#`  y
177     (F# x) >= (F# y) = x `geFloat#`  y
178     (F# x) >  (F# y) = x `gtFloat#`  y
179
180 instance  Num Float  where
181     (+)         x y     =  plusFloat x y
182     (-)         x y     =  minusFloat x y
183     negate      x       =  negateFloat x
184     (*)         x y     =  timesFloat x y
185     abs x | x >= 0.0    =  x
186           | otherwise   =  negateFloat x
187     signum x | x == 0.0  = 0
188              | x > 0.0   = 1
189              | otherwise = negate 1
190
191     {-# INLINE fromInteger #-}
192     fromInteger n       =  encodeFloat n 0
193         -- It's important that encodeFloat inlines here, and that 
194         -- fromInteger in turn inlines,
195         -- so that if fromInteger is applied to an (S# i) the right thing happens
196
197 instance  Real Float  where
198     toRational x        =  (m%1)*(b%1)^^n
199                            where (m,n) = decodeFloat x
200                                  b     = floatRadix  x
201
202 instance  Fractional Float  where
203     (/) x y             =  divideFloat x y
204     fromRational x      =  fromRat x
205     recip x             =  1.0 / x
206
207 {-# RULES "truncate/Float->Int" truncate = float2Int #-}
208 instance  RealFrac Float  where
209
210     {-# SPECIALIZE properFraction :: Float -> (Int, Float) #-}
211     {-# SPECIALIZE round    :: Float -> Int #-}
212
213     {-# SPECIALIZE properFraction :: Float  -> (Integer, Float) #-}
214     {-# SPECIALIZE round    :: Float -> Integer #-}
215
216         -- ceiling, floor, and truncate are all small
217     {-# INLINE ceiling #-}
218     {-# INLINE floor #-}
219     {-# INLINE truncate #-}
220
221     properFraction x
222       = case (decodeFloat x)      of { (m,n) ->
223         let  b = floatRadix x     in
224         if n >= 0 then
225             (fromInteger m * fromInteger b ^ n, 0.0)
226         else
227             case (quotRem m (b^(negate n))) of { (w,r) ->
228             (fromInteger w, encodeFloat r n)
229             }
230         }
231
232     truncate x  = case properFraction x of
233                      (n,_) -> n
234
235     round x     = case properFraction x of
236                      (n,r) -> let
237                                 m         = if r < 0.0 then n - 1 else n + 1
238                                 half_down = abs r - 0.5
239                               in
240                               case (compare half_down 0.0) of
241                                 LT -> n
242                                 EQ -> if even n then n else m
243                                 GT -> m
244
245     ceiling x   = case properFraction x of
246                     (n,r) -> if r > 0.0 then n + 1 else n
247
248     floor x     = case properFraction x of
249                     (n,r) -> if r < 0.0 then n - 1 else n
250
251 instance  Floating Float  where
252     pi                  =  3.141592653589793238
253     exp x               =  expFloat x
254     log x               =  logFloat x
255     sqrt x              =  sqrtFloat x
256     sin x               =  sinFloat x
257     cos x               =  cosFloat x
258     tan x               =  tanFloat x
259     asin x              =  asinFloat x
260     acos x              =  acosFloat x
261     atan x              =  atanFloat x
262     sinh x              =  sinhFloat x
263     cosh x              =  coshFloat x
264     tanh x              =  tanhFloat x
265     (**) x y            =  powerFloat x y
266     logBase x y         =  log y / log x
267
268     asinh x = log (x + sqrt (1.0+x*x))
269     acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
270     atanh x = log ((x+1.0) / sqrt (1.0-x*x))
271
272 instance  RealFloat Float  where
273     floatRadix _        =  FLT_RADIX        -- from float.h
274     floatDigits _       =  FLT_MANT_DIG     -- ditto
275     floatRange _        =  (FLT_MIN_EXP, FLT_MAX_EXP) -- ditto
276
277     decodeFloat (F# f#)
278       = case decodeFloat# f#    of
279           (# exp#, s#, d# #) -> (J# s# d#, I# exp#)
280
281     encodeFloat (S# i) j     = int_encodeFloat# i j
282     encodeFloat (J# s# d#) e = encodeFloat# s# d# e
283
284     exponent x          = case decodeFloat x of
285                             (m,n) -> if m == 0 then 0 else n + floatDigits x
286
287     significand x       = case decodeFloat x of
288                             (m,_) -> encodeFloat m (negate (floatDigits x))
289
290     scaleFloat k x      = case decodeFloat x of
291                             (m,n) -> encodeFloat m (n+k)
292     isNaN x          = 0 /= isFloatNaN x
293     isInfinite x     = 0 /= isFloatInfinite x
294     isDenormalized x = 0 /= isFloatDenormalized x
295     isNegativeZero x = 0 /= isFloatNegativeZero x
296     isIEEE _         = True
297
298 instance  Show Float  where
299     showsPrec   x = showSigned showFloat x
300     showList = showList__ (showsPrec 0) 
301 \end{code}
302
303 %*********************************************************
304 %*                                                      *
305 \subsection{Type @Double@}
306 %*                                                      *
307 %*********************************************************
308
309 \begin{code}
310 instance Eq Double where
311     (D# x) == (D# y) = x ==## y
312
313 instance Ord Double where
314     (D# x) `compare` (D# y) | x <## y   = LT
315                             | x ==## y  = EQ
316                             | otherwise = GT
317
318     (D# x) <  (D# y) = x <##  y
319     (D# x) <= (D# y) = x <=## y
320     (D# x) >= (D# y) = x >=## y
321     (D# x) >  (D# y) = x >##  y
322
323 instance  Num Double  where
324     (+)         x y     =  plusDouble x y
325     (-)         x y     =  minusDouble x y
326     negate      x       =  negateDouble x
327     (*)         x y     =  timesDouble x y
328     abs x | x >= 0.0    =  x
329           | otherwise   =  negateDouble x
330     signum x | x == 0.0  = 0
331              | x > 0.0   = 1
332              | otherwise = negate 1
333
334     {-# INLINE fromInteger #-}
335         -- See comments with Num Float
336     fromInteger (S# i#)    = case (int2Double# i#) of { d# -> D# d# }
337     fromInteger (J# s# d#) = encodeDouble# s# d# 0
338
339
340 instance  Real Double  where
341     toRational x        =  (m%1)*(b%1)^^n
342                            where (m,n) = decodeFloat x
343                                  b     = floatRadix  x
344
345 instance  Fractional Double  where
346     (/) x y             =  divideDouble x y
347     fromRational x      =  fromRat x
348     recip x             =  1.0 / x
349
350 instance  Floating Double  where
351     pi                  =  3.141592653589793238
352     exp x               =  expDouble x
353     log x               =  logDouble x
354     sqrt x              =  sqrtDouble x
355     sin  x              =  sinDouble x
356     cos  x              =  cosDouble x
357     tan  x              =  tanDouble x
358     asin x              =  asinDouble x
359     acos x              =  acosDouble x
360     atan x              =  atanDouble x
361     sinh x              =  sinhDouble x
362     cosh x              =  coshDouble x
363     tanh x              =  tanhDouble x
364     (**) x y            =  powerDouble x y
365     logBase x y         =  log y / log x
366
367     asinh x = log (x + sqrt (1.0+x*x))
368     acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
369     atanh x = log ((x+1.0) / sqrt (1.0-x*x))
370
371 {-# RULES "truncate/Double->Int" truncate = double2Int #-}
372 instance  RealFrac Double  where
373
374     {-# SPECIALIZE properFraction :: Double -> (Int, Double) #-}
375     {-# SPECIALIZE round    :: Double -> Int #-}
376
377     {-# SPECIALIZE properFraction :: Double -> (Integer, Double) #-}
378     {-# SPECIALIZE round    :: Double -> Integer #-}
379
380         -- ceiling, floor, and truncate are all small
381     {-# INLINE ceiling #-}
382     {-# INLINE floor #-}
383     {-# INLINE truncate #-}
384
385     properFraction x
386       = case (decodeFloat x)      of { (m,n) ->
387         let  b = floatRadix x     in
388         if n >= 0 then
389             (fromInteger m * fromInteger b ^ n, 0.0)
390         else
391             case (quotRem m (b^(negate n))) of { (w,r) ->
392             (fromInteger w, encodeFloat r n)
393             }
394         }
395
396     truncate x  = case properFraction x of
397                      (n,_) -> n
398
399     round x     = case properFraction x of
400                      (n,r) -> let
401                                 m         = if r < 0.0 then n - 1 else n + 1
402                                 half_down = abs r - 0.5
403                               in
404                               case (compare half_down 0.0) of
405                                 LT -> n
406                                 EQ -> if even n then n else m
407                                 GT -> m
408
409     ceiling x   = case properFraction x of
410                     (n,r) -> if r > 0.0 then n + 1 else n
411
412     floor x     = case properFraction x of
413                     (n,r) -> if r < 0.0 then n - 1 else n
414
415 instance  RealFloat Double  where
416     floatRadix _        =  FLT_RADIX        -- from float.h
417     floatDigits _       =  DBL_MANT_DIG     -- ditto
418     floatRange _        =  (DBL_MIN_EXP, DBL_MAX_EXP) -- ditto
419
420     decodeFloat (D# x#)
421       = case decodeDouble# x#   of
422           (# exp#, s#, d# #) -> (J# s# d#, I# exp#)
423
424     encodeFloat (S# i) j     = int_encodeDouble# i j
425     encodeFloat (J# s# d#) e = encodeDouble# s# d# e
426
427     exponent x          = case decodeFloat x of
428                             (m,n) -> if m == 0 then 0 else n + floatDigits x
429
430     significand x       = case decodeFloat x of
431                             (m,_) -> encodeFloat m (negate (floatDigits x))
432
433     scaleFloat k x      = case decodeFloat x of
434                             (m,n) -> encodeFloat m (n+k)
435
436     isNaN x             = 0 /= isDoubleNaN x
437     isInfinite x        = 0 /= isDoubleInfinite x
438     isDenormalized x    = 0 /= isDoubleDenormalized x
439     isNegativeZero x    = 0 /= isDoubleNegativeZero x
440     isIEEE _            = True
441
442 instance  Show Double  where
443     showsPrec   x = showSigned showFloat x
444     showList = showList__ (showsPrec 0) 
445 \end{code}
446
447 %*********************************************************
448 %*                                                      *
449 \subsection{@Enum@ instances}
450 %*                                                      *
451 %*********************************************************
452
453 The @Enum@ instances for Floats and Doubles are slightly unusual.
454 The @toEnum@ function truncates numbers to Int.  The definitions
455 of @enumFrom@ and @enumFromThen@ allow floats to be used in arithmetic
456 series: [0,0.1 .. 1.0].  However, roundoff errors make these somewhat
457 dubious.  This example may have either 10 or 11 elements, depending on
458 how 0.1 is represented.
459
460 NOTE: The instances for Float and Double do not make use of the default
461 methods for @enumFromTo@ and @enumFromThenTo@, as these rely on there being
462 a `non-lossy' conversion to and from Ints. Instead we make use of the 
463 1.2 default methods (back in the days when Enum had Ord as a superclass)
464 for these (@numericEnumFromTo@ and @numericEnumFromThenTo@ below.)
465
466 \begin{code}
467 instance  Enum Float  where
468     succ x         = x + 1
469     pred x         = x - 1
470     toEnum         = int2Float
471     fromEnum       = fromInteger . truncate   -- may overflow
472     enumFrom       = numericEnumFrom
473     enumFromTo     = numericEnumFromTo
474     enumFromThen   = numericEnumFromThen
475     enumFromThenTo = numericEnumFromThenTo
476
477 instance  Enum Double  where
478     succ x         = x + 1
479     pred x         = x - 1
480     toEnum         =  int2Double
481     fromEnum       =  fromInteger . truncate   -- may overflow
482     enumFrom       =  numericEnumFrom
483     enumFromTo     =  numericEnumFromTo
484     enumFromThen   =  numericEnumFromThen
485     enumFromThenTo =  numericEnumFromThenTo
486 \end{code}
487
488
489 %*********************************************************
490 %*                                                      *
491 \subsection{Printing floating point}
492 %*                                                      *
493 %*********************************************************
494
495
496 \begin{code}
497 -- | Show a signed 'RealFloat' value to full precision
498 -- using standard decimal notation for arguments whose absolute value lies 
499 -- between @0.1@ and @9,999,999@, and scientific notation otherwise.
500 showFloat :: (RealFloat a) => a -> ShowS
501 showFloat x  =  showString (formatRealFloat FFGeneric Nothing x)
502
503 -- These are the format types.  This type is not exported.
504
505 data FFFormat = FFExponent | FFFixed | FFGeneric
506
507 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
508 formatRealFloat fmt decs x
509    | isNaN x                   = "NaN"
510    | isInfinite x              = if x < 0 then "-Infinity" else "Infinity"
511    | x < 0 || isNegativeZero x = '-':doFmt fmt (floatToDigits (toInteger base) (-x))
512    | otherwise                 = doFmt fmt (floatToDigits (toInteger base) x)
513  where 
514   base = 10
515
516   doFmt format (is, e) =
517     let ds = map intToDigit is in
518     case format of
519      FFGeneric ->
520       doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
521             (is,e)
522      FFExponent ->
523       case decs of
524        Nothing ->
525         let show_e' = show (e-1) in
526         case ds of
527           "0"     -> "0.0e0"
528           [d]     -> d : ".0e" ++ show_e'
529           (d:ds') -> d : '.' : ds' ++ "e" ++ show_e'
530        Just dec ->
531         let dec' = max dec 1 in
532         case is of
533          [0] -> '0' :'.' : take dec' (repeat '0') ++ "e0"
534          _ ->
535           let
536            (ei,is') = roundTo base (dec'+1) is
537            (d:ds') = map intToDigit (if ei > 0 then init is' else is')
538           in
539           d:'.':ds' ++ 'e':show (e-1+ei)
540      FFFixed ->
541       let
542        mk0 ls = case ls of { "" -> "0" ; _ -> ls}
543       in
544       case decs of
545        Nothing
546           | e <= 0    -> "0." ++ replicate (-e) '0' ++ ds
547           | otherwise ->
548              let
549                 f 0 s    rs  = mk0 (reverse s) ++ '.':mk0 rs
550                 f n s    ""  = f (n-1) ('0':s) ""
551                 f n s (r:rs) = f (n-1) (r:s) rs
552              in
553                 f e "" ds
554        Just dec ->
555         let dec' = max dec 0 in
556         if e >= 0 then
557          let
558           (ei,is') = roundTo base (dec' + e) is
559           (ls,rs)  = splitAt (e+ei) (map intToDigit is')
560          in
561          mk0 ls ++ (if null rs then "" else '.':rs)
562         else
563          let
564           (ei,is') = roundTo base dec' (replicate (-e) 0 ++ is)
565           d:ds' = map intToDigit (if ei > 0 then is' else 0:is')
566          in
567          d : (if null ds' then "" else '.':ds')
568
569
570 roundTo :: Int -> Int -> [Int] -> (Int,[Int])
571 roundTo base d is =
572   case f d is of
573     x@(0,_) -> x
574     (1,xs)  -> (1, 1:xs)
575  where
576   b2 = base `div` 2
577
578   f n []     = (0, replicate n 0)
579   f 0 (x:_)  = (if x >= b2 then 1 else 0, [])
580   f n (i:xs)
581      | i' == base = (1,0:ds)
582      | otherwise  = (0,i':ds)
583       where
584        (c,ds) = f (n-1) xs
585        i'     = c + i
586
587 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
588 -- by R.G. Burger and R.K. Dybvig in PLDI 96.
589 -- This version uses a much slower logarithm estimator. It should be improved.
590
591 -- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,
592 -- and returns a list of digits and an exponent. 
593 -- In particular, if @x>=0@, and
594 --
595 -- > floatToDigits base x = ([d1,d2,...,dn], e)
596 --
597 -- then
598 --
599 --      (1) @n >= 1@
600 --
601 --      (2) @x = 0.d1d2...dn * (base**e)@
602 --
603 --      (3) @0 <= di <= base-1@
604
605 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
606 floatToDigits _ 0 = ([0], 0)
607 floatToDigits base x =
608  let 
609   (f0, e0) = decodeFloat x
610   (minExp0, _) = floatRange x
611   p = floatDigits x
612   b = floatRadix x
613   minExp = minExp0 - p -- the real minimum exponent
614   -- Haskell requires that f be adjusted so denormalized numbers
615   -- will have an impossibly low exponent.  Adjust for this.
616   (f, e) = 
617    let n = minExp - e0 in
618    if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
619   (r, s, mUp, mDn) =
620    if e >= 0 then
621     let be = b^ e in
622     if f == b^(p-1) then
623       (f*be*b*2, 2*b, be*b, b)
624     else
625       (f*be*2, 2, be, be)
626    else
627     if e > minExp && f == b^(p-1) then
628       (f*b*2, b^(-e+1)*2, b, 1)
629     else
630       (f*2, b^(-e)*2, 1, 1)
631   k =
632    let 
633     k0 =
634      if b == 2 && base == 10 then
635         -- logBase 10 2 is slightly bigger than 3/10 so
636         -- the following will err on the low side.  Ignoring
637         -- the fraction will make it err even more.
638         -- Haskell promises that p-1 <= logBase b f < p.
639         (p - 1 + e0) * 3 `div` 10
640      else
641         ceiling ((log (fromInteger (f+1)) +
642                  fromInteger (int2Integer e) * log (fromInteger b)) /
643                    log (fromInteger base))
644 --WAS:            fromInt e * log (fromInteger b))
645
646     fixup n =
647       if n >= 0 then
648         if r + mUp <= expt base n * s then n else fixup (n+1)
649       else
650         if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)
651    in
652    fixup k0
653
654   gen ds rn sN mUpN mDnN =
655    let
656     (dn, rn') = (rn * base) `divMod` sN
657     mUpN' = mUpN * base
658     mDnN' = mDnN * base
659    in
660    case (rn' < mDnN', rn' + mUpN' > sN) of
661     (True,  False) -> dn : ds
662     (False, True)  -> dn+1 : ds
663     (True,  True)  -> if rn' * 2 < sN then dn : ds else dn+1 : ds
664     (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
665   
666   rds = 
667    if k >= 0 then
668       gen [] r (s * expt base k) mUp mDn
669    else
670      let bk = expt base (-k) in
671      gen [] (r * bk) s (mUp * bk) (mDn * bk)
672  in
673  (map fromIntegral (reverse rds), k)
674
675 \end{code}
676
677
678 %*********************************************************
679 %*                                                      *
680 \subsection{Converting from a Rational to a RealFloat
681 %*                                                      *
682 %*********************************************************
683
684 [In response to a request for documentation of how fromRational works,
685 Joe Fasel writes:] A quite reasonable request!  This code was added to
686 the Prelude just before the 1.2 release, when Lennart, working with an
687 early version of hbi, noticed that (read . show) was not the identity
688 for floating-point numbers.  (There was a one-bit error about half the
689 time.)  The original version of the conversion function was in fact
690 simply a floating-point divide, as you suggest above. The new version
691 is, I grant you, somewhat denser.
692
693 Unfortunately, Joe's code doesn't work!  Here's an example:
694
695 main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")
696
697 This program prints
698         0.0000000000000000
699 instead of
700         1.8217369128763981e-300
701
702 Here's Joe's code:
703
704 \begin{pseudocode}
705 fromRat :: (RealFloat a) => Rational -> a
706 fromRat x = x'
707         where x' = f e
708
709 --              If the exponent of the nearest floating-point number to x 
710 --              is e, then the significand is the integer nearest xb^(-e),
711 --              where b is the floating-point radix.  We start with a good
712 --              guess for e, and if it is correct, the exponent of the
713 --              floating-point number we construct will again be e.  If
714 --              not, one more iteration is needed.
715
716               f e   = if e' == e then y else f e'
717                       where y      = encodeFloat (round (x * (1 % b)^^e)) e
718                             (_,e') = decodeFloat y
719               b     = floatRadix x'
720
721 --              We obtain a trial exponent by doing a floating-point
722 --              division of x's numerator by its denominator.  The
723 --              result of this division may not itself be the ultimate
724 --              result, because of an accumulation of three rounding
725 --              errors.
726
727               (s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
728                                         / fromInteger (denominator x))
729 \end{pseudocode}
730
731 Now, here's Lennart's code (which works)
732
733 \begin{code}
734 -- | Converts a 'Rational' value into any type in class 'RealFloat'.
735 {-# SPECIALISE fromRat :: Rational -> Double,
736                           Rational -> Float #-}
737 fromRat :: (RealFloat a) => Rational -> a
738
739 -- Deal with special cases first, delegating the real work to fromRat'
740 fromRat (n :% 0) | n > 0  =  1/0        -- +Infinity
741                  | n == 0 =  0/0        -- NaN
742                  | n < 0  = -1/0        -- -Infinity
743
744 fromRat (n :% d) | n > 0  = fromRat' (n :% d)
745                  | n == 0 = encodeFloat 0 0             -- Zero
746                  | n < 0  = - fromRat' ((-n) :% d)
747
748 -- Conversion process:
749 -- Scale the rational number by the RealFloat base until
750 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
751 -- Then round the rational to an Integer and encode it with the exponent
752 -- that we got from the scaling.
753 -- To speed up the scaling process we compute the log2 of the number to get
754 -- a first guess of the exponent.
755
756 fromRat' :: (RealFloat a) => Rational -> a
757 -- Invariant: argument is strictly positive
758 fromRat' x = r
759   where b = floatRadix r
760         p = floatDigits r
761         (minExp0, _) = floatRange r
762         minExp = minExp0 - p            -- the real minimum exponent
763         xMin   = toRational (expt b (p-1))
764         xMax   = toRational (expt b p)
765         p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp
766         f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
767         (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
768         r = encodeFloat (round x') p'
769
770 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
771 scaleRat :: Rational -> Int -> Rational -> Rational -> Int -> Rational -> (Rational, Int)
772 scaleRat b minExp xMin xMax p x 
773  | p <= minExp = (x, p)
774  | x >= xMax   = scaleRat b minExp xMin xMax (p+1) (x/b)
775  | x < xMin    = scaleRat b minExp xMin xMax (p-1) (x*b)
776  | otherwise   = (x, p)
777
778 -- Exponentiation with a cache for the most common numbers.
779 minExpt, maxExpt :: Int
780 minExpt = 0
781 maxExpt = 1100
782
783 expt :: Integer -> Int -> Integer
784 expt base n =
785     if base == 2 && n >= minExpt && n <= maxExpt then
786         expts!n
787     else
788         base^n
789
790 expts :: Array Int Integer
791 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
792
793 -- Compute the (floor of the) log of i in base b.
794 -- Simplest way would be just divide i by b until it's smaller then b, but that would
795 -- be very slow!  We are just slightly more clever.
796 integerLogBase :: Integer -> Integer -> Int
797 integerLogBase b i
798    | i < b     = 0
799    | otherwise = doDiv (i `div` (b^l)) l
800        where
801         -- Try squaring the base first to cut down the number of divisions.
802          l = 2 * integerLogBase (b*b) i
803
804          doDiv :: Integer -> Int -> Int
805          doDiv x y
806             | x < b     = y
807             | otherwise = doDiv (x `div` b) (y+1)
808
809 \end{code}
810
811
812 %*********************************************************
813 %*                                                      *
814 \subsection{Floating point numeric primops}
815 %*                                                      *
816 %*********************************************************
817
818 Definitions of the boxed PrimOps; these will be
819 used in the case of partial applications, etc.
820
821 \begin{code}
822 plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float
823 plusFloat   (F# x) (F# y) = F# (plusFloat# x y)
824 minusFloat  (F# x) (F# y) = F# (minusFloat# x y)
825 timesFloat  (F# x) (F# y) = F# (timesFloat# x y)
826 divideFloat (F# x) (F# y) = F# (divideFloat# x y)
827
828 negateFloat :: Float -> Float
829 negateFloat (F# x)        = F# (negateFloat# x)
830
831 gtFloat, geFloat, eqFloat, neFloat, ltFloat, leFloat :: Float -> Float -> Bool
832 gtFloat     (F# x) (F# y) = gtFloat# x y
833 geFloat     (F# x) (F# y) = geFloat# x y
834 eqFloat     (F# x) (F# y) = eqFloat# x y
835 neFloat     (F# x) (F# y) = neFloat# x y
836 ltFloat     (F# x) (F# y) = ltFloat# x y
837 leFloat     (F# x) (F# y) = leFloat# x y
838
839 float2Int :: Float -> Int
840 float2Int   (F# x) = I# (float2Int# x)
841
842 int2Float :: Int -> Float
843 int2Float   (I# x) = F# (int2Float# x)
844
845 expFloat, logFloat, sqrtFloat :: Float -> Float
846 sinFloat, cosFloat, tanFloat  :: Float -> Float
847 asinFloat, acosFloat, atanFloat  :: Float -> Float
848 sinhFloat, coshFloat, tanhFloat  :: Float -> Float
849 expFloat    (F# x) = F# (expFloat# x)
850 logFloat    (F# x) = F# (logFloat# x)
851 sqrtFloat   (F# x) = F# (sqrtFloat# x)
852 sinFloat    (F# x) = F# (sinFloat# x)
853 cosFloat    (F# x) = F# (cosFloat# x)
854 tanFloat    (F# x) = F# (tanFloat# x)
855 asinFloat   (F# x) = F# (asinFloat# x)
856 acosFloat   (F# x) = F# (acosFloat# x)
857 atanFloat   (F# x) = F# (atanFloat# x)
858 sinhFloat   (F# x) = F# (sinhFloat# x)
859 coshFloat   (F# x) = F# (coshFloat# x)
860 tanhFloat   (F# x) = F# (tanhFloat# x)
861
862 powerFloat :: Float -> Float -> Float
863 powerFloat  (F# x) (F# y) = F# (powerFloat# x y)
864
865 -- definitions of the boxed PrimOps; these will be
866 -- used in the case of partial applications, etc.
867
868 plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double
869 plusDouble   (D# x) (D# y) = D# (x +## y)
870 minusDouble  (D# x) (D# y) = D# (x -## y)
871 timesDouble  (D# x) (D# y) = D# (x *## y)
872 divideDouble (D# x) (D# y) = D# (x /## y)
873
874 negateDouble :: Double -> Double
875 negateDouble (D# x)        = D# (negateDouble# x)
876
877 gtDouble, geDouble, eqDouble, neDouble, leDouble, ltDouble :: Double -> Double -> Bool
878 gtDouble    (D# x) (D# y) = x >## y
879 geDouble    (D# x) (D# y) = x >=## y
880 eqDouble    (D# x) (D# y) = x ==## y
881 neDouble    (D# x) (D# y) = x /=## y
882 ltDouble    (D# x) (D# y) = x <## y
883 leDouble    (D# x) (D# y) = x <=## y
884
885 double2Int :: Double -> Int
886 double2Int   (D# x) = I# (double2Int#   x)
887
888 int2Double :: Int -> Double
889 int2Double   (I# x) = D# (int2Double#   x)
890
891 double2Float :: Double -> Float
892 double2Float (D# x) = F# (double2Float# x)
893
894 float2Double :: Float -> Double
895 float2Double (F# x) = D# (float2Double# x)
896
897 expDouble, logDouble, sqrtDouble :: Double -> Double
898 sinDouble, cosDouble, tanDouble  :: Double -> Double
899 asinDouble, acosDouble, atanDouble  :: Double -> Double
900 sinhDouble, coshDouble, tanhDouble  :: Double -> Double
901 expDouble    (D# x) = D# (expDouble# x)
902 logDouble    (D# x) = D# (logDouble# x)
903 sqrtDouble   (D# x) = D# (sqrtDouble# x)
904 sinDouble    (D# x) = D# (sinDouble# x)
905 cosDouble    (D# x) = D# (cosDouble# x)
906 tanDouble    (D# x) = D# (tanDouble# x)
907 asinDouble   (D# x) = D# (asinDouble# x)
908 acosDouble   (D# x) = D# (acosDouble# x)
909 atanDouble   (D# x) = D# (atanDouble# x)
910 sinhDouble   (D# x) = D# (sinhDouble# x)
911 coshDouble   (D# x) = D# (coshDouble# x)
912 tanhDouble   (D# x) = D# (tanhDouble# x)
913
914 powerDouble :: Double -> Double -> Double
915 powerDouble  (D# x) (D# y) = D# (x **## y)
916 \end{code}
917
918 \begin{code}
919 foreign import ccall unsafe "__encodeFloat"
920         encodeFloat# :: Int# -> ByteArray# -> Int -> Float
921 foreign import ccall unsafe "__int_encodeFloat"
922         int_encodeFloat# :: Int# -> Int -> Float
923
924
925 foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int
926 foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int
927 foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int
928 foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int
929
930
931 foreign import ccall unsafe "__encodeDouble"
932         encodeDouble# :: Int# -> ByteArray# -> Int -> Double
933 foreign import ccall unsafe "__int_encodeDouble"
934         int_encodeDouble# :: Int# -> Int -> Double
935
936 foreign import ccall unsafe "isDoubleNaN" isDoubleNaN :: Double -> Int
937 foreign import ccall unsafe "isDoubleInfinite" isDoubleInfinite :: Double -> Int
938 foreign import ccall unsafe "isDoubleDenormalized" isDoubleDenormalized :: Double -> Int
939 foreign import ccall unsafe "isDoubleNegativeZero" isDoubleNegativeZero :: Double -> Int
940 \end{code}
941
942 %*********************************************************
943 %*                                                      *
944 \subsection{Coercion rules}
945 %*                                                      *
946 %*********************************************************
947
948 \begin{code}
949 {-# RULES
950 "fromIntegral/Int->Float"   fromIntegral = int2Float
951 "fromIntegral/Int->Double"  fromIntegral = int2Double
952 "realToFrac/Float->Float"   realToFrac   = id :: Float -> Float
953 "realToFrac/Float->Double"  realToFrac   = float2Double
954 "realToFrac/Double->Float"  realToFrac   = double2Float
955 "realToFrac/Double->Double" realToFrac   = id :: Double -> Double
956     #-}
957 \end{code}