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