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