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