[project @ 2004-02-12 14:55:31 by simonpj]
[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 --
541 -- @
542 --      floatToDigits base x = ([d1,d2,...,dn], e)
543 -- @
544 --
545 -- then
546 --
547 --      (1) n >= 1
548 --
549 --      (2) x = 0.d1d2...dn * (base**e)
550 --
551 --      (3) 0 <= di <= base-1
552
553 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
554 floatToDigits _ 0 = ([0], 0)
555 floatToDigits base x =
556  let 
557   (f0, e0) = decodeFloat x
558   (minExp0, _) = floatRange x
559   p = floatDigits x
560   b = floatRadix x
561   minExp = minExp0 - p -- the real minimum exponent
562   -- Haskell requires that f be adjusted so denormalized numbers
563   -- will have an impossibly low exponent.  Adjust for this.
564   (f, e) = 
565    let n = minExp - e0 in
566    if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
567   (r, s, mUp, mDn) =
568    if e >= 0 then
569     let be = b^ e in
570     if f == b^(p-1) then
571       (f*be*b*2, 2*b, be*b, b)
572     else
573       (f*be*2, 2, be, be)
574    else
575     if e > minExp && f == b^(p-1) then
576       (f*b*2, b^(-e+1)*2, b, 1)
577     else
578       (f*2, b^(-e)*2, 1, 1)
579   k =
580    let 
581     k0 =
582      if b == 2 && base == 10 then
583         -- logBase 10 2 is slightly bigger than 3/10 so
584         -- the following will err on the low side.  Ignoring
585         -- the fraction will make it err even more.
586         -- Haskell promises that p-1 <= logBase b f < p.
587         (p - 1 + e0) * 3 `div` 10
588      else
589         ceiling ((log (fromInteger (f+1)) +
590                  fromInteger (int2Integer e) * log (fromInteger b)) /
591                    log (fromInteger base))
592 --WAS:            fromInt e * log (fromInteger b))
593
594     fixup n =
595       if n >= 0 then
596         if r + mUp <= expt base n * s then n else fixup (n+1)
597       else
598         if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)
599    in
600    fixup k0
601
602   gen ds rn sN mUpN mDnN =
603    let
604     (dn, rn') = (rn * base) `divMod` sN
605     mUpN' = mUpN * base
606     mDnN' = mDnN * base
607    in
608    case (rn' < mDnN', rn' + mUpN' > sN) of
609     (True,  False) -> dn : ds
610     (False, True)  -> dn+1 : ds
611     (True,  True)  -> if rn' * 2 < sN then dn : ds else dn+1 : ds
612     (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
613   
614   rds = 
615    if k >= 0 then
616       gen [] r (s * expt base k) mUp mDn
617    else
618      let bk = expt base (-k) in
619      gen [] (r * bk) s (mUp * bk) (mDn * bk)
620  in
621  (map fromIntegral (reverse rds), k)
622
623 \end{code}
624
625
626 %*********************************************************
627 %*                                                      *
628 \subsection{Converting from a Rational to a RealFloat
629 %*                                                      *
630 %*********************************************************
631
632 [In response to a request for documentation of how fromRational works,
633 Joe Fasel writes:] A quite reasonable request!  This code was added to
634 the Prelude just before the 1.2 release, when Lennart, working with an
635 early version of hbi, noticed that (read . show) was not the identity
636 for floating-point numbers.  (There was a one-bit error about half the
637 time.)  The original version of the conversion function was in fact
638 simply a floating-point divide, as you suggest above. The new version
639 is, I grant you, somewhat denser.
640
641 Unfortunately, Joe's code doesn't work!  Here's an example:
642
643 main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")
644
645 This program prints
646         0.0000000000000000
647 instead of
648         1.8217369128763981e-300
649
650 Here's Joe's code:
651
652 \begin{pseudocode}
653 fromRat :: (RealFloat a) => Rational -> a
654 fromRat x = x'
655         where x' = f e
656
657 --              If the exponent of the nearest floating-point number to x 
658 --              is e, then the significand is the integer nearest xb^(-e),
659 --              where b is the floating-point radix.  We start with a good
660 --              guess for e, and if it is correct, the exponent of the
661 --              floating-point number we construct will again be e.  If
662 --              not, one more iteration is needed.
663
664               f e   = if e' == e then y else f e'
665                       where y      = encodeFloat (round (x * (1 % b)^^e)) e
666                             (_,e') = decodeFloat y
667               b     = floatRadix x'
668
669 --              We obtain a trial exponent by doing a floating-point
670 --              division of x's numerator by its denominator.  The
671 --              result of this division may not itself be the ultimate
672 --              result, because of an accumulation of three rounding
673 --              errors.
674
675               (s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
676                                         / fromInteger (denominator x))
677 \end{pseudocode}
678
679 Now, here's Lennart's code (which works)
680
681 \begin{code}
682 {-# SPECIALISE fromRat :: Rational -> Double,
683                           Rational -> Float #-}
684 fromRat :: (RealFloat a) => Rational -> a
685
686 -- Deal with special cases first, delegating the real work to fromRat'
687 fromRat (n :% 0) | n > 0  =  1/0        -- +Infinity
688                  | n == 0 =  0/0        -- NaN
689                  | n < 0  = -1/0        -- -Infinity
690
691 fromRat (n :% d) | n > 0  = fromRat' (n :% d)
692                  | n == 0 = encodeFloat 0 0             -- Zero
693                  | n < 0  = - fromRat' ((-n) :% d)
694
695 -- Conversion process:
696 -- Scale the rational number by the RealFloat base until
697 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
698 -- Then round the rational to an Integer and encode it with the exponent
699 -- that we got from the scaling.
700 -- To speed up the scaling process we compute the log2 of the number to get
701 -- a first guess of the exponent.
702
703 fromRat' :: (RealFloat a) => Rational -> a
704 -- Invariant: argument is strictly positive
705 fromRat' x = r
706   where b = floatRadix r
707         p = floatDigits r
708         (minExp0, _) = floatRange r
709         minExp = minExp0 - p            -- the real minimum exponent
710         xMin   = toRational (expt b (p-1))
711         xMax   = toRational (expt b p)
712         p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp
713         f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
714         (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
715         r = encodeFloat (round x') p'
716
717 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
718 scaleRat :: Rational -> Int -> Rational -> Rational -> Int -> Rational -> (Rational, Int)
719 scaleRat b minExp xMin xMax p x 
720  | p <= minExp = (x, p)
721  | x >= xMax   = scaleRat b minExp xMin xMax (p+1) (x/b)
722  | x < xMin    = scaleRat b minExp xMin xMax (p-1) (x*b)
723  | otherwise   = (x, p)
724
725 -- Exponentiation with a cache for the most common numbers.
726 minExpt, maxExpt :: Int
727 minExpt = 0
728 maxExpt = 1100
729
730 expt :: Integer -> Int -> Integer
731 expt base n =
732     if base == 2 && n >= minExpt && n <= maxExpt then
733         expts!n
734     else
735         base^n
736
737 expts :: Array Int Integer
738 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
739
740 -- Compute the (floor of the) log of i in base b.
741 -- Simplest way would be just divide i by b until it's smaller then b, but that would
742 -- be very slow!  We are just slightly more clever.
743 integerLogBase :: Integer -> Integer -> Int
744 integerLogBase b i
745    | i < b     = 0
746    | otherwise = doDiv (i `div` (b^l)) l
747        where
748         -- Try squaring the base first to cut down the number of divisions.
749          l = 2 * integerLogBase (b*b) i
750
751          doDiv :: Integer -> Int -> Int
752          doDiv x y
753             | x < b     = y
754             | otherwise = doDiv (x `div` b) (y+1)
755
756 \end{code}
757
758
759 %*********************************************************
760 %*                                                      *
761 \subsection{Floating point numeric primops}
762 %*                                                      *
763 %*********************************************************
764
765 Definitions of the boxed PrimOps; these will be
766 used in the case of partial applications, etc.
767
768 \begin{code}
769 plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float
770 plusFloat   (F# x) (F# y) = F# (plusFloat# x y)
771 minusFloat  (F# x) (F# y) = F# (minusFloat# x y)
772 timesFloat  (F# x) (F# y) = F# (timesFloat# x y)
773 divideFloat (F# x) (F# y) = F# (divideFloat# x y)
774
775 negateFloat :: Float -> Float
776 negateFloat (F# x)        = F# (negateFloat# x)
777
778 gtFloat, geFloat, eqFloat, neFloat, ltFloat, leFloat :: Float -> Float -> Bool
779 gtFloat     (F# x) (F# y) = gtFloat# x y
780 geFloat     (F# x) (F# y) = geFloat# x y
781 eqFloat     (F# x) (F# y) = eqFloat# x y
782 neFloat     (F# x) (F# y) = neFloat# x y
783 ltFloat     (F# x) (F# y) = ltFloat# x y
784 leFloat     (F# x) (F# y) = leFloat# x y
785
786 float2Int :: Float -> Int
787 float2Int   (F# x) = I# (float2Int# x)
788
789 int2Float :: Int -> Float
790 int2Float   (I# x) = F# (int2Float# x)
791
792 expFloat, logFloat, sqrtFloat :: Float -> Float
793 sinFloat, cosFloat, tanFloat  :: Float -> Float
794 asinFloat, acosFloat, atanFloat  :: Float -> Float
795 sinhFloat, coshFloat, tanhFloat  :: Float -> Float
796 expFloat    (F# x) = F# (expFloat# x)
797 logFloat    (F# x) = F# (logFloat# x)
798 sqrtFloat   (F# x) = F# (sqrtFloat# x)
799 sinFloat    (F# x) = F# (sinFloat# x)
800 cosFloat    (F# x) = F# (cosFloat# x)
801 tanFloat    (F# x) = F# (tanFloat# x)
802 asinFloat   (F# x) = F# (asinFloat# x)
803 acosFloat   (F# x) = F# (acosFloat# x)
804 atanFloat   (F# x) = F# (atanFloat# x)
805 sinhFloat   (F# x) = F# (sinhFloat# x)
806 coshFloat   (F# x) = F# (coshFloat# x)
807 tanhFloat   (F# x) = F# (tanhFloat# x)
808
809 powerFloat :: Float -> Float -> Float
810 powerFloat  (F# x) (F# y) = F# (powerFloat# x y)
811
812 -- definitions of the boxed PrimOps; these will be
813 -- used in the case of partial applications, etc.
814
815 plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double
816 plusDouble   (D# x) (D# y) = D# (x +## y)
817 minusDouble  (D# x) (D# y) = D# (x -## y)
818 timesDouble  (D# x) (D# y) = D# (x *## y)
819 divideDouble (D# x) (D# y) = D# (x /## y)
820
821 negateDouble :: Double -> Double
822 negateDouble (D# x)        = D# (negateDouble# x)
823
824 gtDouble, geDouble, eqDouble, neDouble, leDouble, ltDouble :: Double -> Double -> Bool
825 gtDouble    (D# x) (D# y) = x >## y
826 geDouble    (D# x) (D# y) = x >=## y
827 eqDouble    (D# x) (D# y) = x ==## y
828 neDouble    (D# x) (D# y) = x /=## y
829 ltDouble    (D# x) (D# y) = x <## y
830 leDouble    (D# x) (D# y) = x <=## y
831
832 double2Int :: Double -> Int
833 double2Int   (D# x) = I# (double2Int#   x)
834
835 int2Double :: Int -> Double
836 int2Double   (I# x) = D# (int2Double#   x)
837
838 double2Float :: Double -> Float
839 double2Float (D# x) = F# (double2Float# x)
840
841 float2Double :: Float -> Double
842 float2Double (F# x) = D# (float2Double# x)
843
844 expDouble, logDouble, sqrtDouble :: Double -> Double
845 sinDouble, cosDouble, tanDouble  :: Double -> Double
846 asinDouble, acosDouble, atanDouble  :: Double -> Double
847 sinhDouble, coshDouble, tanhDouble  :: Double -> Double
848 expDouble    (D# x) = D# (expDouble# x)
849 logDouble    (D# x) = D# (logDouble# x)
850 sqrtDouble   (D# x) = D# (sqrtDouble# x)
851 sinDouble    (D# x) = D# (sinDouble# x)
852 cosDouble    (D# x) = D# (cosDouble# x)
853 tanDouble    (D# x) = D# (tanDouble# x)
854 asinDouble   (D# x) = D# (asinDouble# x)
855 acosDouble   (D# x) = D# (acosDouble# x)
856 atanDouble   (D# x) = D# (atanDouble# x)
857 sinhDouble   (D# x) = D# (sinhDouble# x)
858 coshDouble   (D# x) = D# (coshDouble# x)
859 tanhDouble   (D# x) = D# (tanhDouble# x)
860
861 powerDouble :: Double -> Double -> Double
862 powerDouble  (D# x) (D# y) = D# (x **## y)
863 \end{code}
864
865 \begin{code}
866 foreign import ccall unsafe "__encodeFloat"
867         encodeFloat# :: Int# -> ByteArray# -> Int -> Float
868 foreign import ccall unsafe "__int_encodeFloat"
869         int_encodeFloat# :: Int# -> Int -> Float
870
871
872 foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int
873 foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int
874 foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int
875 foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int
876
877
878 foreign import ccall unsafe "__encodeDouble"
879         encodeDouble# :: Int# -> ByteArray# -> Int -> Double
880 foreign import ccall unsafe "__int_encodeDouble"
881         int_encodeDouble# :: Int# -> Int -> Double
882
883 foreign import ccall unsafe "isDoubleNaN" isDoubleNaN :: Double -> Int
884 foreign import ccall unsafe "isDoubleInfinite" isDoubleInfinite :: Double -> Int
885 foreign import ccall unsafe "isDoubleDenormalized" isDoubleDenormalized :: Double -> Int
886 foreign import ccall unsafe "isDoubleNegativeZero" isDoubleNegativeZero :: Double -> Int
887 \end{code}
888
889 %*********************************************************
890 %*                                                      *
891 \subsection{Coercion rules}
892 %*                                                      *
893 %*********************************************************
894
895 \begin{code}
896 {-# RULES
897 "fromIntegral/Int->Float"   fromIntegral = int2Float
898 "fromIntegral/Int->Double"  fromIntegral = int2Double
899 "realToFrac/Float->Float"   realToFrac   = id :: Float -> Float
900 "realToFrac/Float->Double"  realToFrac   = float2Double
901 "realToFrac/Double->Float"  realToFrac   = double2Float
902 "realToFrac/Double->Double" realToFrac   = id :: Double -> Double
903     #-}
904 \end{code}