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