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