Fix warnings
[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# )  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           []      -> error "formatRealFloat/doFmt/FFExponent: []"
524        Just dec ->
525         let dec' = max dec 1 in
526         case is of
527          [0] -> '0' :'.' : take dec' (repeat '0') ++ "e0"
528          _ ->
529           let
530            (ei,is') = roundTo base (dec'+1) is
531            (d:ds') = map intToDigit (if ei > 0 then init is' else is')
532           in
533           d:'.':ds' ++ 'e':show (e-1+ei)
534      FFFixed ->
535       let
536        mk0 ls = case ls of { "" -> "0" ; _ -> ls}
537       in
538       case decs of
539        Nothing
540           | e <= 0    -> "0." ++ replicate (-e) '0' ++ ds
541           | otherwise ->
542              let
543                 f 0 s    rs  = mk0 (reverse s) ++ '.':mk0 rs
544                 f n s    ""  = f (n-1) ('0':s) ""
545                 f n s (r:rs) = f (n-1) (r:s) rs
546              in
547                 f e "" ds
548        Just dec ->
549         let dec' = max dec 0 in
550         if e >= 0 then
551          let
552           (ei,is') = roundTo base (dec' + e) is
553           (ls,rs)  = splitAt (e+ei) (map intToDigit is')
554          in
555          mk0 ls ++ (if null rs then "" else '.':rs)
556         else
557          let
558           (ei,is') = roundTo base dec' (replicate (-e) 0 ++ is)
559           d:ds' = map intToDigit (if ei > 0 then is' else 0:is')
560          in
561          d : (if null ds' then "" else '.':ds')
562
563
564 roundTo :: Int -> Int -> [Int] -> (Int,[Int])
565 roundTo base d is =
566   case f d is of
567     x@(0,_) -> x
568     (1,xs)  -> (1, 1:xs)
569     _       -> error "roundTo: bad Value"
570  where
571   b2 = base `div` 2
572
573   f n []     = (0, replicate n 0)
574   f 0 (x:_)  = (if x >= b2 then 1 else 0, [])
575   f n (i:xs)
576      | i' == base = (1,0:ds)
577      | otherwise  = (0,i':ds)
578       where
579        (c,ds) = f (n-1) xs
580        i'     = c + i
581
582 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
583 -- by R.G. Burger and R.K. Dybvig in PLDI 96.
584 -- This version uses a much slower logarithm estimator. It should be improved.
585
586 -- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,
587 -- and returns a list of digits and an exponent. 
588 -- In particular, if @x>=0@, and
589 --
590 -- > floatToDigits base x = ([d1,d2,...,dn], e)
591 --
592 -- then
593 --
594 --      (1) @n >= 1@
595 --
596 --      (2) @x = 0.d1d2...dn * (base**e)@
597 --
598 --      (3) @0 <= di <= base-1@
599
600 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
601 floatToDigits _ 0 = ([0], 0)
602 floatToDigits base x =
603  let 
604   (f0, e0) = decodeFloat x
605   (minExp0, _) = floatRange x
606   p = floatDigits x
607   b = floatRadix x
608   minExp = minExp0 - p -- the real minimum exponent
609   -- Haskell requires that f be adjusted so denormalized numbers
610   -- will have an impossibly low exponent.  Adjust for this.
611   (f, e) = 
612    let n = minExp - e0 in
613    if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
614   (r, s, mUp, mDn) =
615    if e >= 0 then
616     let be = b^ e in
617     if f == b^(p-1) then
618       (f*be*b*2, 2*b, be*b, b)
619     else
620       (f*be*2, 2, be, be)
621    else
622     if e > minExp && f == b^(p-1) then
623       (f*b*2, b^(-e+1)*2, b, 1)
624     else
625       (f*2, b^(-e)*2, 1, 1)
626   k :: Int
627   k =
628    let 
629     k0 :: Int
630     k0 =
631      if b == 2 && base == 10 then
632         -- logBase 10 2 is slightly bigger than 3/10 so
633         -- the following will err on the low side.  Ignoring
634         -- the fraction will make it err even more.
635         -- Haskell promises that p-1 <= logBase b f < p.
636         (p - 1 + e0) * 3 `div` 10
637      else
638         ceiling ((log (fromInteger (f+1)) +
639                  fromIntegral e * log (fromInteger b)) /
640                    log (fromInteger base))
641 --WAS:            fromInt e * log (fromInteger b))
642
643     fixup n =
644       if n >= 0 then
645         if r + mUp <= expt base n * s then n else fixup (n+1)
646       else
647         if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)
648    in
649    fixup k0
650
651   gen ds rn sN mUpN mDnN =
652    let
653     (dn, rn') = (rn * base) `divMod` sN
654     mUpN' = mUpN * base
655     mDnN' = mDnN * base
656    in
657    case (rn' < mDnN', rn' + mUpN' > sN) of
658     (True,  False) -> dn : ds
659     (False, True)  -> dn+1 : ds
660     (True,  True)  -> if rn' * 2 < sN then dn : ds else dn+1 : ds
661     (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
662   
663   rds = 
664    if k >= 0 then
665       gen [] r (s * expt base k) mUp mDn
666    else
667      let bk = expt base (-k) in
668      gen [] (r * bk) s (mUp * bk) (mDn * bk)
669  in
670  (map fromIntegral (reverse rds), k)
671
672 \end{code}
673
674
675 %*********************************************************
676 %*                                                      *
677 \subsection{Converting from a Rational to a RealFloat
678 %*                                                      *
679 %*********************************************************
680
681 [In response to a request for documentation of how fromRational works,
682 Joe Fasel writes:] A quite reasonable request!  This code was added to
683 the Prelude just before the 1.2 release, when Lennart, working with an
684 early version of hbi, noticed that (read . show) was not the identity
685 for floating-point numbers.  (There was a one-bit error about half the
686 time.)  The original version of the conversion function was in fact
687 simply a floating-point divide, as you suggest above. The new version
688 is, I grant you, somewhat denser.
689
690 Unfortunately, Joe's code doesn't work!  Here's an example:
691
692 main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")
693
694 This program prints
695         0.0000000000000000
696 instead of
697         1.8217369128763981e-300
698
699 Here's Joe's code:
700
701 \begin{pseudocode}
702 fromRat :: (RealFloat a) => Rational -> a
703 fromRat x = x'
704         where x' = f e
705
706 --              If the exponent of the nearest floating-point number to x 
707 --              is e, then the significand is the integer nearest xb^(-e),
708 --              where b is the floating-point radix.  We start with a good
709 --              guess for e, and if it is correct, the exponent of the
710 --              floating-point number we construct will again be e.  If
711 --              not, one more iteration is needed.
712
713               f e   = if e' == e then y else f e'
714                       where y      = encodeFloat (round (x * (1 % b)^^e)) e
715                             (_,e') = decodeFloat y
716               b     = floatRadix x'
717
718 --              We obtain a trial exponent by doing a floating-point
719 --              division of x's numerator by its denominator.  The
720 --              result of this division may not itself be the ultimate
721 --              result, because of an accumulation of three rounding
722 --              errors.
723
724               (s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
725                                         / fromInteger (denominator x))
726 \end{pseudocode}
727
728 Now, here's Lennart's code (which works)
729
730 \begin{code}
731 -- | Converts a 'Rational' value into any type in class 'RealFloat'.
732 {-# SPECIALISE fromRat :: Rational -> Double,
733                           Rational -> Float #-}
734 fromRat :: (RealFloat a) => Rational -> a
735
736 -- Deal with special cases first, delegating the real work to fromRat'
737 fromRat (n :% 0) | n > 0     =  1/0        -- +Infinity
738                  | n < 0     = -1/0        -- -Infinity
739                  | otherwise =  0/0        -- NaN
740
741 fromRat (n :% d) | n > 0     = fromRat' (n :% d)
742                  | n < 0     = - fromRat' ((-n) :% d)
743                  | otherwise = encodeFloat 0 0             -- Zero
744
745 -- Conversion process:
746 -- Scale the rational number by the RealFloat base until
747 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
748 -- Then round the rational to an Integer and encode it with the exponent
749 -- that we got from the scaling.
750 -- To speed up the scaling process we compute the log2 of the number to get
751 -- a first guess of the exponent.
752
753 fromRat' :: (RealFloat a) => Rational -> a
754 -- Invariant: argument is strictly positive
755 fromRat' x = r
756   where b = floatRadix r
757         p = floatDigits r
758         (minExp0, _) = floatRange r
759         minExp = minExp0 - p            -- the real minimum exponent
760         xMin   = toRational (expt b (p-1))
761         xMax   = toRational (expt b p)
762         p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp
763         f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
764         (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
765         r = encodeFloat (round x') p'
766
767 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
768 scaleRat :: Rational -> Int -> Rational -> Rational -> Int -> Rational -> (Rational, Int)
769 scaleRat b minExp xMin xMax p x 
770  | p <= minExp = (x, p)
771  | x >= xMax   = scaleRat b minExp xMin xMax (p+1) (x/b)
772  | x < xMin    = scaleRat b minExp xMin xMax (p-1) (x*b)
773  | otherwise   = (x, p)
774
775 -- Exponentiation with a cache for the most common numbers.
776 minExpt, maxExpt :: Int
777 minExpt = 0
778 maxExpt = 1100
779
780 expt :: Integer -> Int -> Integer
781 expt base n =
782     if base == 2 && n >= minExpt && n <= maxExpt then
783         expts!n
784     else
785         base^n
786
787 expts :: Array Int Integer
788 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
789
790 -- Compute the (floor of the) log of i in base b.
791 -- Simplest way would be just divide i by b until it's smaller then b, but that would
792 -- be very slow!  We are just slightly more clever.
793 integerLogBase :: Integer -> Integer -> Int
794 integerLogBase b i
795    | i < b     = 0
796    | otherwise = doDiv (i `div` (b^l)) l
797        where
798         -- Try squaring the base first to cut down the number of divisions.
799          l = 2 * integerLogBase (b*b) i
800
801          doDiv :: Integer -> Int -> Int
802          doDiv x y
803             | x < b     = y
804             | otherwise = doDiv (x `div` b) (y+1)
805
806 \end{code}
807
808
809 %*********************************************************
810 %*                                                      *
811 \subsection{Floating point numeric primops}
812 %*                                                      *
813 %*********************************************************
814
815 Definitions of the boxed PrimOps; these will be
816 used in the case of partial applications, etc.
817
818 \begin{code}
819 plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float
820 plusFloat   (F# x) (F# y) = F# (plusFloat# x y)
821 minusFloat  (F# x) (F# y) = F# (minusFloat# x y)
822 timesFloat  (F# x) (F# y) = F# (timesFloat# x y)
823 divideFloat (F# x) (F# y) = F# (divideFloat# x y)
824
825 negateFloat :: Float -> Float
826 negateFloat (F# x)        = F# (negateFloat# x)
827
828 gtFloat, geFloat, eqFloat, neFloat, ltFloat, leFloat :: Float -> Float -> Bool
829 gtFloat     (F# x) (F# y) = gtFloat# x y
830 geFloat     (F# x) (F# y) = geFloat# x y
831 eqFloat     (F# x) (F# y) = eqFloat# x y
832 neFloat     (F# x) (F# y) = neFloat# x y
833 ltFloat     (F# x) (F# y) = ltFloat# x y
834 leFloat     (F# x) (F# y) = leFloat# x y
835
836 float2Int :: Float -> Int
837 float2Int   (F# x) = I# (float2Int# x)
838
839 int2Float :: Int -> Float
840 int2Float   (I# x) = F# (int2Float# x)
841
842 expFloat, logFloat, sqrtFloat :: Float -> Float
843 sinFloat, cosFloat, tanFloat  :: Float -> Float
844 asinFloat, acosFloat, atanFloat  :: Float -> Float
845 sinhFloat, coshFloat, tanhFloat  :: Float -> Float
846 expFloat    (F# x) = F# (expFloat# x)
847 logFloat    (F# x) = F# (logFloat# x)
848 sqrtFloat   (F# x) = F# (sqrtFloat# x)
849 sinFloat    (F# x) = F# (sinFloat# x)
850 cosFloat    (F# x) = F# (cosFloat# x)
851 tanFloat    (F# x) = F# (tanFloat# x)
852 asinFloat   (F# x) = F# (asinFloat# x)
853 acosFloat   (F# x) = F# (acosFloat# x)
854 atanFloat   (F# x) = F# (atanFloat# x)
855 sinhFloat   (F# x) = F# (sinhFloat# x)
856 coshFloat   (F# x) = F# (coshFloat# x)
857 tanhFloat   (F# x) = F# (tanhFloat# x)
858
859 powerFloat :: Float -> Float -> Float
860 powerFloat  (F# x) (F# y) = F# (powerFloat# x y)
861
862 -- definitions of the boxed PrimOps; these will be
863 -- used in the case of partial applications, etc.
864
865 plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double
866 plusDouble   (D# x) (D# y) = D# (x +## y)
867 minusDouble  (D# x) (D# y) = D# (x -## y)
868 timesDouble  (D# x) (D# y) = D# (x *## y)
869 divideDouble (D# x) (D# y) = D# (x /## y)
870
871 negateDouble :: Double -> Double
872 negateDouble (D# x)        = D# (negateDouble# x)
873
874 gtDouble, geDouble, eqDouble, neDouble, leDouble, ltDouble :: Double -> Double -> Bool
875 gtDouble    (D# x) (D# y) = x >## y
876 geDouble    (D# x) (D# y) = x >=## y
877 eqDouble    (D# x) (D# y) = x ==## y
878 neDouble    (D# x) (D# y) = x /=## y
879 ltDouble    (D# x) (D# y) = x <## y
880 leDouble    (D# x) (D# y) = x <=## y
881
882 double2Int :: Double -> Int
883 double2Int   (D# x) = I# (double2Int#   x)
884
885 int2Double :: Int -> Double
886 int2Double   (I# x) = D# (int2Double#   x)
887
888 double2Float :: Double -> Float
889 double2Float (D# x) = F# (double2Float# x)
890
891 float2Double :: Float -> Double
892 float2Double (F# x) = D# (float2Double# x)
893
894 expDouble, logDouble, sqrtDouble :: Double -> Double
895 sinDouble, cosDouble, tanDouble  :: Double -> Double
896 asinDouble, acosDouble, atanDouble  :: Double -> Double
897 sinhDouble, coshDouble, tanhDouble  :: Double -> Double
898 expDouble    (D# x) = D# (expDouble# x)
899 logDouble    (D# x) = D# (logDouble# x)
900 sqrtDouble   (D# x) = D# (sqrtDouble# x)
901 sinDouble    (D# x) = D# (sinDouble# x)
902 cosDouble    (D# x) = D# (cosDouble# x)
903 tanDouble    (D# x) = D# (tanDouble# x)
904 asinDouble   (D# x) = D# (asinDouble# x)
905 acosDouble   (D# x) = D# (acosDouble# x)
906 atanDouble   (D# x) = D# (atanDouble# x)
907 sinhDouble   (D# x) = D# (sinhDouble# x)
908 coshDouble   (D# x) = D# (coshDouble# x)
909 tanhDouble   (D# x) = D# (tanhDouble# x)
910
911 powerDouble :: Double -> Double -> Double
912 powerDouble  (D# x) (D# y) = D# (x **## y)
913 \end{code}
914
915 \begin{code}
916 foreign import ccall unsafe "__encodeFloat"
917         encodeFloat# :: Int# -> ByteArray# -> Int -> Float
918 foreign import ccall unsafe "__int_encodeFloat"
919         int_encodeFloat# :: Int# -> Int -> Float
920
921
922 foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int
923 foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int
924 foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int
925 foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int
926
927
928 foreign import ccall unsafe "__encodeDouble"
929         encodeDouble# :: Int# -> ByteArray# -> Int -> Double
930
931 foreign import ccall unsafe "isDoubleNaN" isDoubleNaN :: Double -> Int
932 foreign import ccall unsafe "isDoubleInfinite" isDoubleInfinite :: Double -> Int
933 foreign import ccall unsafe "isDoubleDenormalized" isDoubleDenormalized :: Double -> Int
934 foreign import ccall unsafe "isDoubleNegativeZero" isDoubleNegativeZero :: Double -> Int
935 \end{code}
936
937 %*********************************************************
938 %*                                                      *
939 \subsection{Coercion rules}
940 %*                                                      *
941 %*********************************************************
942
943 \begin{code}
944 {-# RULES
945 "fromIntegral/Int->Float"   fromIntegral = int2Float
946 "fromIntegral/Int->Double"  fromIntegral = int2Double
947 "realToFrac/Float->Float"   realToFrac   = id :: Float -> Float
948 "realToFrac/Float->Double"  realToFrac   = float2Double
949 "realToFrac/Double->Float"  realToFrac   = double2Float
950 "realToFrac/Double->Double" realToFrac   = id :: Double -> Double
951 "realToFrac/Int->Double"    realToFrac   = int2Double   -- See Note [realToFrac int-to-float]
952 "realToFrac/Int->Float"     realToFrac   = int2Float    --      ..ditto
953     #-}
954 \end{code}
955
956 Note [realToFrac int-to-float]
957 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
958 Don found that the RULES for realToFrac/Int->Double and simliarly
959 Float made a huge difference to some stream-fusion programs.  Here's
960 an example
961   
962       import Data.Array.Vector
963   
964       n = 40000000
965   
966       main = do
967             let c = replicateU n (2::Double)
968                 a = mapU realToFrac (enumFromToU 0 (n-1) ) :: UArr Double
969             print (sumU (zipWithU (*) c a))
970   
971 Without the RULE we get this loop body:
972   
973       case $wtoRational sc_sY4 of ww_aM7 { (# ww1_aM9, ww2_aMa #) ->
974       case $wfromRat ww1_aM9 ww2_aMa of tpl_X1P { D# ipv_sW3 ->
975       Main.$s$wfold
976         (+# sc_sY4 1)
977         (+# wild_X1i 1)
978         (+## sc2_sY6 (*## 2.0 ipv_sW3))
979   
980 And with the rule:
981   
982      Main.$s$wfold
983         (+# sc_sXT 1)
984         (+# wild_X1h 1)
985         (+## sc2_sXV (*## 2.0 (int2Double# sc_sXT)))
986   
987 The running time of the program goes from 120 seconds to 0.198 seconds
988 with the native backend, and 0.143 seconds with the C backend.
989   
990 A few more details in Trac #2251, and the patch message 
991 "Add RULES for realToFrac from Int".
992
993 %*********************************************************
994 %*                                                      *
995 \subsection{Utils}
996 %*                                                      *
997 %*********************************************************
998
999 \begin{code}
1000 showSignedFloat :: (RealFloat a)
1001   => (a -> ShowS)       -- ^ a function that can show unsigned values
1002   -> Int                -- ^ the precedence of the enclosing context
1003   -> a                  -- ^ the value to show
1004   -> ShowS
1005 showSignedFloat showPos p x
1006    | x < 0 || isNegativeZero x
1007        = showParen (p > 6) (showChar '-' . showPos (-x))
1008    | otherwise = showPos x
1009 \end{code}