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