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