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