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