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