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