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