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