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