6 , ForeignFunctionInterface
8 -- We believe we could deorphan this module, by moving lots of things
9 -- around, but we haven't got there yet:
10 {-# OPTIONS_GHC -fno-warn-orphans #-}
11 {-# OPTIONS_HADDOCK hide #-}
13 -----------------------------------------------------------------------------
16 -- Copyright : (c) The University of Glasgow 1994-2002
17 -- License : see libraries/base/LICENSE
19 -- Maintainer : cvs-ghc@haskell.org
20 -- Stability : internal
21 -- Portability : non-portable (GHC Extensions)
23 -- The types 'Float' and 'Double', and the classes 'Floating' and 'RealFloat'.
25 -----------------------------------------------------------------------------
27 #include "ieee-flpt.h"
30 module GHC.Float( module GHC.Float, Float(..), Double(..), Float#, Double#
31 , double2Int, int2Double, float2Int, int2Float )
44 import GHC.Float.RealFracMethods
49 %*********************************************************
51 \subsection{Standard numeric classes}
53 %*********************************************************
56 -- | Trigonometric and hyperbolic functions and related functions.
58 -- Minimal complete definition:
59 -- 'pi', 'exp', 'log', 'sin', 'cos', 'sinh', 'cosh',
60 -- 'asin', 'acos', 'atan', 'asinh', 'acosh' and 'atanh'
61 class (Fractional a) => Floating a where
63 exp, log, sqrt :: a -> a
64 (**), logBase :: a -> a -> a
65 sin, cos, tan :: a -> a
66 asin, acos, atan :: a -> a
67 sinh, cosh, tanh :: a -> a
68 asinh, acosh, atanh :: a -> a
71 {-# INLINE logBase #-}
75 x ** y = exp (log x * y)
76 logBase x y = log y / log x
79 tanh x = sinh x / cosh x
81 -- | Efficient, machine-independent access to the components of a
82 -- floating-point number.
84 -- Minimal complete definition:
85 -- all except 'exponent', 'significand', 'scaleFloat' and 'atan2'
86 class (RealFrac a, Floating a) => RealFloat a where
87 -- | a constant function, returning the radix of the representation
89 floatRadix :: a -> Integer
90 -- | a constant function, returning the number of digits of
91 -- 'floatRadix' in the significand
92 floatDigits :: a -> Int
93 -- | a constant function, returning the lowest and highest values
94 -- the exponent may assume
95 floatRange :: a -> (Int,Int)
96 -- | The function 'decodeFloat' applied to a real floating-point
97 -- number returns the significand expressed as an 'Integer' and an
98 -- appropriately scaled exponent (an 'Int'). If @'decodeFloat' x@
99 -- yields @(m,n)@, then @x@ is equal in value to @m*b^^n@, where @b@
100 -- is the floating-point radix, and furthermore, either @m@ and @n@
101 -- are both zero or else @b^(d-1) <= m < b^d@, where @d@ is the value
102 -- of @'floatDigits' x@. In particular, @'decodeFloat' 0 = (0,0)@.
103 decodeFloat :: a -> (Integer,Int)
104 -- | 'encodeFloat' performs the inverse of 'decodeFloat'
105 encodeFloat :: Integer -> Int -> a
106 -- | the second component of 'decodeFloat'.
108 -- | the first component of 'decodeFloat', scaled to lie in the open
109 -- interval (@-1@,@1@)
110 significand :: a -> a
111 -- | multiplies a floating-point number by an integer power of the radix
112 scaleFloat :: Int -> a -> a
113 -- | 'True' if the argument is an IEEE \"not-a-number\" (NaN) value
115 -- | 'True' if the argument is an IEEE infinity or negative infinity
116 isInfinite :: a -> Bool
117 -- | 'True' if the argument is too small to be represented in
119 isDenormalized :: a -> Bool
120 -- | 'True' if the argument is an IEEE negative zero
121 isNegativeZero :: a -> Bool
122 -- | 'True' if the argument is an IEEE floating point number
124 -- | a version of arctangent taking two real floating-point arguments.
125 -- For real floating @x@ and @y@, @'atan2' y x@ computes the angle
126 -- (from the positive x-axis) of the vector from the origin to the
127 -- point @(x,y)@. @'atan2' y x@ returns a value in the range [@-pi@,
128 -- @pi@]. It follows the Common Lisp semantics for the origin when
129 -- signed zeroes are supported. @'atan2' y 1@, with @y@ in a type
130 -- that is 'RealFloat', should return the same value as @'atan' y@.
131 -- A default definition of 'atan2' is provided, but implementors
132 -- can provide a more accurate implementation.
136 exponent x = if m == 0 then 0 else n + floatDigits x
137 where (m,n) = decodeFloat x
139 significand x = encodeFloat m (negate (floatDigits x))
140 where (m,_) = decodeFloat x
142 scaleFloat k x = encodeFloat m (n + clamp b k)
143 where (m,n) = decodeFloat x
147 -- n+k may overflow, which would lead
148 -- to wrong results, hence we clamp the
149 -- scaling parameter.
150 -- If n + k would be larger than h,
151 -- n + clamp b k must be too, simliar
152 -- for smaller than l - d.
153 -- Add a little extra to keep clear
154 -- from the boundary cases.
158 | x == 0 && y > 0 = pi/2
159 | x < 0 && y > 0 = pi + atan (y/x)
160 |(x <= 0 && y < 0) ||
161 (x < 0 && isNegativeZero y) ||
162 (isNegativeZero x && isNegativeZero y)
164 | y == 0 && (x < 0 || isNegativeZero x)
165 = pi -- must be after the previous test on zero y
166 | x==0 && y==0 = y -- must be after the other double zero tests
167 | otherwise = x + y -- x or y is a NaN, return a NaN (via +)
171 %*********************************************************
173 \subsection{Type @Float@}
175 %*********************************************************
178 instance Num Float where
179 (+) x y = plusFloat x y
180 (-) x y = minusFloat x y
181 negate x = negateFloat x
182 (*) x y = timesFloat x y
184 | otherwise = negateFloat x
185 signum x | x == 0.0 = 0
187 | otherwise = negate 1
189 {-# INLINE fromInteger #-}
190 fromInteger i = F# (floatFromInteger i)
192 instance Real Float where
193 toRational x = (m%1)*(b%1)^^n
194 where (m,n) = decodeFloat x
197 instance Fractional Float where
198 (/) x y = divideFloat x y
199 fromRational x = fromRat x
202 -- RULES for Integer and Int
204 "properFraction/Float->Integer" properFraction = properFractionFloatInteger
205 "truncate/Float->Integer" truncate = truncateFloatInteger
206 "floor/Float->Integer" floor = floorFloatInteger
207 "ceiling/Float->Integer" ceiling = ceilingFloatInteger
208 "round/Float->Integer" round = roundFloatInteger
209 "properFraction/Float->Int" properFraction = properFractionFloatInt
210 "truncate/Float->Int" truncate = float2Int
211 "floor/Float->Int" floor = floorFloatInt
212 "ceiling/Float->Int" ceiling = ceilingFloatInt
213 "round/Float->Int" round = roundFloatInt
215 instance RealFrac Float where
217 -- ceiling, floor, and truncate are all small
218 {-# INLINE [1] ceiling #-}
219 {-# INLINE [1] floor #-}
220 {-# INLINE [1] truncate #-}
222 -- We assume that FLT_RADIX is 2 so that we can use more efficient code
224 #error FLT_RADIX must be 2
226 properFraction (F# x#)
227 = case decodeFloat_Int# x# of
233 then (fromIntegral m * (2 ^ n), 0.0)
234 else let i = if m >= 0 then m `shiftR` negate n
235 else negate (negate m `shiftR` negate n)
236 f = m - (i `shiftL` negate n)
237 in (fromIntegral i, encodeFloat (fromIntegral f) n)
239 truncate x = case properFraction x of
242 round x = case properFraction x of
244 m = if r < 0.0 then n - 1 else n + 1
245 half_down = abs r - 0.5
247 case (compare half_down 0.0) of
249 EQ -> if even n then n else m
252 ceiling x = case properFraction x of
253 (n,r) -> if r > 0.0 then n + 1 else n
255 floor x = case properFraction x of
256 (n,r) -> if r < 0.0 then n - 1 else n
258 instance Floating Float where
259 pi = 3.141592653589793238
272 (**) x y = powerFloat x y
273 logBase x y = log y / log x
275 asinh x = log (x + sqrt (1.0+x*x))
276 acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
277 atanh x = 0.5 * log ((1.0+x) / (1.0-x))
279 instance RealFloat Float where
280 floatRadix _ = FLT_RADIX -- from float.h
281 floatDigits _ = FLT_MANT_DIG -- ditto
282 floatRange _ = (FLT_MIN_EXP, FLT_MAX_EXP) -- ditto
284 decodeFloat (F# f#) = case decodeFloat_Int# f# of
285 (# i, e #) -> (smallInteger i, I# e)
287 encodeFloat i (I# e) = F# (encodeFloatInteger i e)
289 exponent x = case decodeFloat x of
290 (m,n) -> if m == 0 then 0 else n + floatDigits x
292 significand x = case decodeFloat x of
293 (m,_) -> encodeFloat m (negate (floatDigits x))
295 scaleFloat k x = case decodeFloat x of
296 (m,n) -> encodeFloat m (n + clamp bf k)
297 where bf = FLT_MAX_EXP - (FLT_MIN_EXP) + 4*FLT_MANT_DIG
299 isNaN x = 0 /= isFloatNaN x
300 isInfinite x = 0 /= isFloatInfinite x
301 isDenormalized x = 0 /= isFloatDenormalized x
302 isNegativeZero x = 0 /= isFloatNegativeZero x
305 instance Show Float where
306 showsPrec x = showSignedFloat showFloat x
307 showList = showList__ (showsPrec 0)
310 %*********************************************************
312 \subsection{Type @Double@}
314 %*********************************************************
317 instance Num Double where
318 (+) x y = plusDouble x y
319 (-) x y = minusDouble x y
320 negate x = negateDouble x
321 (*) x y = timesDouble x y
323 | otherwise = negateDouble x
324 signum x | x == 0.0 = 0
326 | otherwise = negate 1
328 {-# INLINE fromInteger #-}
329 fromInteger i = D# (doubleFromInteger i)
332 instance Real Double where
333 toRational x = (m%1)*(b%1)^^n
334 where (m,n) = decodeFloat x
337 instance Fractional Double where
338 (/) x y = divideDouble x y
339 fromRational x = fromRat x
342 instance Floating Double where
343 pi = 3.141592653589793238
346 sqrt x = sqrtDouble x
350 asin x = asinDouble x
351 acos x = acosDouble x
352 atan x = atanDouble x
353 sinh x = sinhDouble x
354 cosh x = coshDouble x
355 tanh x = tanhDouble x
356 (**) x y = powerDouble x y
357 logBase x y = log y / log x
359 asinh x = log (x + sqrt (1.0+x*x))
360 acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
361 atanh x = 0.5 * log ((1.0+x) / (1.0-x))
363 -- RULES for Integer and Int
365 "properFraction/Double->Integer" properFraction = properFractionDoubleInteger
366 "truncate/Double->Integer" truncate = truncateDoubleInteger
367 "floor/Double->Integer" floor = floorDoubleInteger
368 "ceiling/Double->Integer" ceiling = ceilingDoubleInteger
369 "round/Double->Integer" round = roundDoubleInteger
370 "properFraction/Double->Int" properFraction = properFractionDoubleInt
371 "truncate/Double->Int" truncate = double2Int
372 "floor/Double->Int" floor = floorDoubleInt
373 "ceiling/Double->Int" ceiling = ceilingDoubleInt
374 "round/Double->Int" round = roundDoubleInt
376 instance RealFrac Double where
378 -- ceiling, floor, and truncate are all small
379 {-# INLINE [1] ceiling #-}
380 {-# INLINE [1] floor #-}
381 {-# INLINE [1] truncate #-}
384 = case (decodeFloat x) of { (m,n) ->
386 (fromInteger m * 2 ^ n, 0.0)
388 case (quotRem m (2^(negate n))) of { (w,r) ->
389 (fromInteger w, encodeFloat r n)
393 truncate x = case properFraction x of
396 round x = case properFraction x of
398 m = if r < 0.0 then n - 1 else n + 1
399 half_down = abs r - 0.5
401 case (compare half_down 0.0) of
403 EQ -> if even n then n else m
406 ceiling x = case properFraction x of
407 (n,r) -> if r > 0.0 then n + 1 else n
409 floor x = case properFraction x of
410 (n,r) -> if r < 0.0 then n - 1 else n
412 instance RealFloat Double where
413 floatRadix _ = FLT_RADIX -- from float.h
414 floatDigits _ = DBL_MANT_DIG -- ditto
415 floatRange _ = (DBL_MIN_EXP, DBL_MAX_EXP) -- ditto
418 = case decodeDoubleInteger x# of
419 (# i, j #) -> (i, I# j)
421 encodeFloat i (I# j) = D# (encodeDoubleInteger i j)
423 exponent x = case decodeFloat x of
424 (m,n) -> if m == 0 then 0 else n + floatDigits x
426 significand x = case decodeFloat x of
427 (m,_) -> encodeFloat m (negate (floatDigits x))
429 scaleFloat k x = case decodeFloat x of
430 (m,n) -> encodeFloat m (n + clamp bd k)
431 where bd = DBL_MAX_EXP - (DBL_MIN_EXP) + 4*DBL_MANT_DIG
433 isNaN x = 0 /= isDoubleNaN x
434 isInfinite x = 0 /= isDoubleInfinite x
435 isDenormalized x = 0 /= isDoubleDenormalized x
436 isNegativeZero x = 0 /= isDoubleNegativeZero x
439 instance Show Double where
440 showsPrec x = showSignedFloat showFloat x
441 showList = showList__ (showsPrec 0)
444 %*********************************************************
446 \subsection{@Enum@ instances}
448 %*********************************************************
450 The @Enum@ instances for Floats and Doubles are slightly unusual.
451 The @toEnum@ function truncates numbers to Int. The definitions
452 of @enumFrom@ and @enumFromThen@ allow floats to be used in arithmetic
453 series: [0,0.1 .. 1.0]. However, roundoff errors make these somewhat
454 dubious. This example may have either 10 or 11 elements, depending on
455 how 0.1 is represented.
457 NOTE: The instances for Float and Double do not make use of the default
458 methods for @enumFromTo@ and @enumFromThenTo@, as these rely on there being
459 a `non-lossy' conversion to and from Ints. Instead we make use of the
460 1.2 default methods (back in the days when Enum had Ord as a superclass)
461 for these (@numericEnumFromTo@ and @numericEnumFromThenTo@ below.)
464 instance Enum Float where
468 fromEnum = fromInteger . truncate -- may overflow
469 enumFrom = numericEnumFrom
470 enumFromTo = numericEnumFromTo
471 enumFromThen = numericEnumFromThen
472 enumFromThenTo = numericEnumFromThenTo
474 instance Enum Double where
478 fromEnum = fromInteger . truncate -- may overflow
479 enumFrom = numericEnumFrom
480 enumFromTo = numericEnumFromTo
481 enumFromThen = numericEnumFromThen
482 enumFromThenTo = numericEnumFromThenTo
486 %*********************************************************
488 \subsection{Printing floating point}
490 %*********************************************************
494 -- | Show a signed 'RealFloat' value to full precision
495 -- using standard decimal notation for arguments whose absolute value lies
496 -- between @0.1@ and @9,999,999@, and scientific notation otherwise.
497 showFloat :: (RealFloat a) => a -> ShowS
498 showFloat x = showString (formatRealFloat FFGeneric Nothing x)
500 -- These are the format types. This type is not exported.
502 data FFFormat = FFExponent | FFFixed | FFGeneric
504 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
505 formatRealFloat fmt decs x
507 | isInfinite x = if x < 0 then "-Infinity" else "Infinity"
508 | x < 0 || isNegativeZero x = '-':doFmt fmt (floatToDigits (toInteger base) (-x))
509 | otherwise = doFmt fmt (floatToDigits (toInteger base) x)
513 doFmt format (is, e) =
514 let ds = map intToDigit is in
517 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
522 let show_e' = show (e-1) in
525 [d] -> d : ".0e" ++ show_e'
526 (d:ds') -> d : '.' : ds' ++ "e" ++ show_e'
527 [] -> error "formatRealFloat/doFmt/FFExponent: []"
529 let dec' = max dec 1 in
531 [0] -> '0' :'.' : take dec' (repeat '0') ++ "e0"
534 (ei,is') = roundTo base (dec'+1) is
535 (d:ds') = map intToDigit (if ei > 0 then init is' else is')
537 d:'.':ds' ++ 'e':show (e-1+ei)
540 mk0 ls = case ls of { "" -> "0" ; _ -> ls}
544 | e <= 0 -> "0." ++ replicate (-e) '0' ++ ds
547 f 0 s rs = mk0 (reverse s) ++ '.':mk0 rs
548 f n s "" = f (n-1) ('0':s) ""
549 f n s (r:rs) = f (n-1) (r:s) rs
553 let dec' = max dec 0 in
556 (ei,is') = roundTo base (dec' + e) is
557 (ls,rs) = splitAt (e+ei) (map intToDigit is')
559 mk0 ls ++ (if null rs then "" else '.':rs)
562 (ei,is') = roundTo base dec' (replicate (-e) 0 ++ is)
563 d:ds' = map intToDigit (if ei > 0 then is' else 0:is')
565 d : (if null ds' then "" else '.':ds')
568 roundTo :: Int -> Int -> [Int] -> (Int,[Int])
573 _ -> error "roundTo: bad Value"
577 f n [] = (0, replicate n 0)
578 f 0 (x:_) = (if x >= b2 then 1 else 0, [])
580 | i' == base = (1,0:ds)
581 | otherwise = (0,i':ds)
586 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
587 -- by R.G. Burger and R.K. Dybvig in PLDI 96.
588 -- This version uses a much slower logarithm estimator. It should be improved.
590 -- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,
591 -- and returns a list of digits and an exponent.
592 -- In particular, if @x>=0@, and
594 -- > floatToDigits base x = ([d1,d2,...,dn], e)
600 -- (2) @x = 0.d1d2...dn * (base**e)@
602 -- (3) @0 <= di <= base-1@
604 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
605 floatToDigits _ 0 = ([0], 0)
606 floatToDigits base x =
608 (f0, e0) = decodeFloat x
609 (minExp0, _) = floatRange x
612 minExp = minExp0 - p -- the real minimum exponent
613 -- Haskell requires that f be adjusted so denormalized numbers
614 -- will have an impossibly low exponent. Adjust for this.
616 let n = minExp - e0 in
617 if n > 0 then (f0 `quot` (expt b n), e0+n) else (f0, e0)
621 if f == expt b (p-1) then
622 (f*be*b*2, 2*b, be*b, be) -- according to Burger and Dybvig
626 if e > minExp && f == expt b (p-1) then
627 (f*b*2, expt b (-e+1)*2, b, 1)
629 (f*2, expt b (-e)*2, 1, 1)
635 if b == 2 && base == 10 then
636 -- logBase 10 2 is very slightly larger than 8651/28738
637 -- (about 5.3558e-10), so if log x >= 0, the approximation
638 -- k1 is too small, hence we add one and need one fixup step less.
639 -- If log x < 0, the approximation errs rather on the high side.
640 -- That is usually more than compensated for by ignoring the
641 -- fractional part of logBase 2 x, but when x is a power of 1/2
642 -- or slightly larger and the exponent is a multiple of the
643 -- denominator of the rational approximation to logBase 10 2,
644 -- k1 is larger than logBase 10 x. If k1 > 1 + logBase 10 x,
645 -- we get a leading zero-digit we don't want.
646 -- With the approximation 3/10, this happened for
647 -- 0.5^1030, 0.5^1040, ..., 0.5^1070 and values close above.
648 -- The approximation 8651/28738 guarantees k1 < 1 + logBase 10 x
649 -- for IEEE-ish floating point types with exponent fields
650 -- <= 17 bits and mantissae of several thousand bits, earlier
651 -- convergents to logBase 10 2 would fail for long double.
652 -- Using quot instead of div is a little faster and requires
653 -- fewer fixup steps for negative lx.
655 k1 = (lx * 8651) `quot` 28738
656 in if lx >= 0 then k1 + 1 else k1
658 -- f :: Integer, log :: Float -> Float,
659 -- ceiling :: Float -> Int
660 ceiling ((log (fromInteger (f+1) :: Float) +
661 fromIntegral e * log (fromInteger b)) /
662 log (fromInteger base))
663 --WAS: fromInt e * log (fromInteger b))
667 if r + mUp <= expt base n * s then n else fixup (n+1)
669 if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)
673 gen ds rn sN mUpN mDnN =
675 (dn, rn') = (rn * base) `quotRem` sN
679 case (rn' < mDnN', rn' + mUpN' > sN) of
680 (True, False) -> dn : ds
681 (False, True) -> dn+1 : ds
682 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
683 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
687 gen [] r (s * expt base k) mUp mDn
689 let bk = expt base (-k) in
690 gen [] (r * bk) s (mUp * bk) (mDn * bk)
692 (map fromIntegral (reverse rds), k)
697 %*********************************************************
699 \subsection{Converting from a Rational to a RealFloat
701 %*********************************************************
703 [In response to a request for documentation of how fromRational works,
704 Joe Fasel writes:] A quite reasonable request! This code was added to
705 the Prelude just before the 1.2 release, when Lennart, working with an
706 early version of hbi, noticed that (read . show) was not the identity
707 for floating-point numbers. (There was a one-bit error about half the
708 time.) The original version of the conversion function was in fact
709 simply a floating-point divide, as you suggest above. The new version
710 is, I grant you, somewhat denser.
712 Unfortunately, Joe's code doesn't work! Here's an example:
714 main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")
719 1.8217369128763981e-300
724 fromRat :: (RealFloat a) => Rational -> a
728 -- If the exponent of the nearest floating-point number to x
729 -- is e, then the significand is the integer nearest xb^(-e),
730 -- where b is the floating-point radix. We start with a good
731 -- guess for e, and if it is correct, the exponent of the
732 -- floating-point number we construct will again be e. If
733 -- not, one more iteration is needed.
735 f e = if e' == e then y else f e'
736 where y = encodeFloat (round (x * (1 % b)^^e)) e
737 (_,e') = decodeFloat y
740 -- We obtain a trial exponent by doing a floating-point
741 -- division of x's numerator by its denominator. The
742 -- result of this division may not itself be the ultimate
743 -- result, because of an accumulation of three rounding
746 (s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
747 / fromInteger (denominator x))
750 Now, here's Lennart's code (which works)
753 -- | Converts a 'Rational' value into any type in class 'RealFloat'.
754 {-# SPECIALISE fromRat :: Rational -> Double,
755 Rational -> Float #-}
756 fromRat :: (RealFloat a) => Rational -> a
758 -- Deal with special cases first, delegating the real work to fromRat'
759 fromRat (n :% 0) | n > 0 = 1/0 -- +Infinity
760 | n < 0 = -1/0 -- -Infinity
761 | otherwise = 0/0 -- NaN
763 fromRat (n :% d) | n > 0 = fromRat' (n :% d)
764 | n < 0 = - fromRat' ((-n) :% d)
765 | otherwise = encodeFloat 0 0 -- Zero
767 -- Conversion process:
768 -- Scale the rational number by the RealFloat base until
769 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
770 -- Then round the rational to an Integer and encode it with the exponent
771 -- that we got from the scaling.
772 -- To speed up the scaling process we compute the log2 of the number to get
773 -- a first guess of the exponent.
775 fromRat' :: (RealFloat a) => Rational -> a
776 -- Invariant: argument is strictly positive
778 where b = floatRadix r
780 (minExp0, _) = floatRange r
781 minExp = minExp0 - p -- the real minimum exponent
782 xMin = toRational (expt b (p-1))
783 xMax = toRational (expt b p)
784 p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp
785 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
786 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
787 r = encodeFloat (round x') p'
789 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
790 scaleRat :: Rational -> Int -> Rational -> Rational -> Int -> Rational -> (Rational, Int)
791 scaleRat b minExp xMin xMax p x
792 | p <= minExp = (x, p)
793 | x >= xMax = scaleRat b minExp xMin xMax (p+1) (x/b)
794 | x < xMin = scaleRat b minExp xMin xMax (p-1) (x*b)
797 -- Exponentiation with a cache for the most common numbers.
798 minExpt, maxExpt :: Int
802 expt :: Integer -> Int -> Integer
804 if base == 2 && n >= minExpt && n <= maxExpt then
807 if base == 10 && n <= maxExpt10 then
812 expts :: Array Int Integer
813 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
818 expts10 :: Array Int Integer
819 expts10 = array (minExpt,maxExpt10) [(n,10^n) | n <- [minExpt .. maxExpt10]]
821 -- Compute the (floor of the) log of i in base b.
822 -- Simplest way would be just divide i by b until it's smaller then b, but that would
823 -- be very slow! We are just slightly more clever.
824 integerLogBase :: Integer -> Integer -> Int
827 | otherwise = doDiv (i `div` (b^l)) l
829 -- Try squaring the base first to cut down the number of divisions.
830 l = 2 * integerLogBase (b*b) i
832 doDiv :: Integer -> Int -> Int
835 | otherwise = doDiv (x `div` b) (y+1)
840 %*********************************************************
842 \subsection{Floating point numeric primops}
844 %*********************************************************
846 Definitions of the boxed PrimOps; these will be
847 used in the case of partial applications, etc.
850 plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float
851 plusFloat (F# x) (F# y) = F# (plusFloat# x y)
852 minusFloat (F# x) (F# y) = F# (minusFloat# x y)
853 timesFloat (F# x) (F# y) = F# (timesFloat# x y)
854 divideFloat (F# x) (F# y) = F# (divideFloat# x y)
856 negateFloat :: Float -> Float
857 negateFloat (F# x) = F# (negateFloat# x)
859 gtFloat, geFloat, eqFloat, neFloat, ltFloat, leFloat :: Float -> Float -> Bool
860 gtFloat (F# x) (F# y) = gtFloat# x y
861 geFloat (F# x) (F# y) = geFloat# x y
862 eqFloat (F# x) (F# y) = eqFloat# x y
863 neFloat (F# x) (F# y) = neFloat# x y
864 ltFloat (F# x) (F# y) = ltFloat# x y
865 leFloat (F# x) (F# y) = leFloat# x y
867 expFloat, logFloat, sqrtFloat :: Float -> Float
868 sinFloat, cosFloat, tanFloat :: Float -> Float
869 asinFloat, acosFloat, atanFloat :: Float -> Float
870 sinhFloat, coshFloat, tanhFloat :: Float -> Float
871 expFloat (F# x) = F# (expFloat# x)
872 logFloat (F# x) = F# (logFloat# x)
873 sqrtFloat (F# x) = F# (sqrtFloat# x)
874 sinFloat (F# x) = F# (sinFloat# x)
875 cosFloat (F# x) = F# (cosFloat# x)
876 tanFloat (F# x) = F# (tanFloat# x)
877 asinFloat (F# x) = F# (asinFloat# x)
878 acosFloat (F# x) = F# (acosFloat# x)
879 atanFloat (F# x) = F# (atanFloat# x)
880 sinhFloat (F# x) = F# (sinhFloat# x)
881 coshFloat (F# x) = F# (coshFloat# x)
882 tanhFloat (F# x) = F# (tanhFloat# x)
884 powerFloat :: Float -> Float -> Float
885 powerFloat (F# x) (F# y) = F# (powerFloat# x y)
887 -- definitions of the boxed PrimOps; these will be
888 -- used in the case of partial applications, etc.
890 plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double
891 plusDouble (D# x) (D# y) = D# (x +## y)
892 minusDouble (D# x) (D# y) = D# (x -## y)
893 timesDouble (D# x) (D# y) = D# (x *## y)
894 divideDouble (D# x) (D# y) = D# (x /## y)
896 negateDouble :: Double -> Double
897 negateDouble (D# x) = D# (negateDouble# x)
899 gtDouble, geDouble, eqDouble, neDouble, leDouble, ltDouble :: Double -> Double -> Bool
900 gtDouble (D# x) (D# y) = x >## y
901 geDouble (D# x) (D# y) = x >=## y
902 eqDouble (D# x) (D# y) = x ==## y
903 neDouble (D# x) (D# y) = x /=## y
904 ltDouble (D# x) (D# y) = x <## y
905 leDouble (D# x) (D# y) = x <=## y
907 double2Float :: Double -> Float
908 double2Float (D# x) = F# (double2Float# x)
910 float2Double :: Float -> Double
911 float2Double (F# x) = D# (float2Double# x)
913 expDouble, logDouble, sqrtDouble :: Double -> Double
914 sinDouble, cosDouble, tanDouble :: Double -> Double
915 asinDouble, acosDouble, atanDouble :: Double -> Double
916 sinhDouble, coshDouble, tanhDouble :: Double -> Double
917 expDouble (D# x) = D# (expDouble# x)
918 logDouble (D# x) = D# (logDouble# x)
919 sqrtDouble (D# x) = D# (sqrtDouble# x)
920 sinDouble (D# x) = D# (sinDouble# x)
921 cosDouble (D# x) = D# (cosDouble# x)
922 tanDouble (D# x) = D# (tanDouble# x)
923 asinDouble (D# x) = D# (asinDouble# x)
924 acosDouble (D# x) = D# (acosDouble# x)
925 atanDouble (D# x) = D# (atanDouble# x)
926 sinhDouble (D# x) = D# (sinhDouble# x)
927 coshDouble (D# x) = D# (coshDouble# x)
928 tanhDouble (D# x) = D# (tanhDouble# x)
930 powerDouble :: Double -> Double -> Double
931 powerDouble (D# x) (D# y) = D# (x **## y)
935 foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int
936 foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int
937 foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int
938 foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int
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
947 %*********************************************************
949 \subsection{Coercion rules}
951 %*********************************************************
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 "realToFrac/Int->Double" realToFrac = int2Double -- See Note [realToFrac int-to-float]
962 "realToFrac/Int->Float" realToFrac = int2Float -- ..ditto
966 Note [realToFrac int-to-float]
967 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
968 Don found that the RULES for realToFrac/Int->Double and simliarly
969 Float made a huge difference to some stream-fusion programs. Here's
972 import Data.Array.Vector
977 let c = replicateU n (2::Double)
978 a = mapU realToFrac (enumFromToU 0 (n-1) ) :: UArr Double
979 print (sumU (zipWithU (*) c a))
981 Without the RULE we get this loop body:
983 case $wtoRational sc_sY4 of ww_aM7 { (# ww1_aM9, ww2_aMa #) ->
984 case $wfromRat ww1_aM9 ww2_aMa of tpl_X1P { D# ipv_sW3 ->
988 (+## sc2_sY6 (*## 2.0 ipv_sW3))
995 (+## sc2_sXV (*## 2.0 (int2Double# sc_sXT)))
997 The running time of the program goes from 120 seconds to 0.198 seconds
998 with the native backend, and 0.143 seconds with the C backend.
1000 A few more details in Trac #2251, and the patch message
1001 "Add RULES for realToFrac from Int".
1003 %*********************************************************
1007 %*********************************************************
1010 showSignedFloat :: (RealFloat a)
1011 => (a -> ShowS) -- ^ a function that can show unsigned values
1012 -> Int -- ^ the precedence of the enclosing context
1013 -> a -- ^ the value to show
1015 showSignedFloat showPos p x
1016 | x < 0 || isNegativeZero x
1017 = showParen (p > 6) (showChar '-' . showPos (-x))
1018 | otherwise = showPos x
1021 We need to prevent over/underflow of the exponent in encodeFloat when
1022 called from scaleFloat, hence we clamp the scaling parameter.
1023 We must have a large enough range to cover the maximum difference of
1024 exponents returned by decodeFloat.
1026 clamp :: Int -> Int -> Int
1027 clamp bd k = max (-bd) (min bd k)