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