2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
7 -- Copyright : (c) The University of Glasgow 1994-2002
8 -- License : see libraries/base/LICENSE
10 -- Maintainer : cvs-ghc@haskell.org
11 -- Stability : internal
12 -- Portability : non-portable (GHC Extensions)
14 -- The types 'Float' and 'Double', and the classes 'Floating' and 'RealFloat'.
16 -----------------------------------------------------------------------------
18 #include "ieee-flpt.h"
21 module GHC.Float( module GHC.Float, Float(..), Double(..), Float#, Double# )
37 %*********************************************************
39 \subsection{Standard numeric classes}
41 %*********************************************************
44 -- | Trigonometric and hyperbolic functions and related functions.
46 -- Minimal complete definition:
47 -- 'pi', 'exp', 'log', 'sin', 'cos', 'sinh', 'cosh',
48 -- 'asin', 'acos', 'atan', 'asinh', 'acosh' and 'atanh'
49 class (Fractional a) => Floating a where
51 exp, log, sqrt :: a -> a
52 (**), logBase :: a -> a -> a
53 sin, cos, tan :: a -> a
54 asin, acos, atan :: a -> a
55 sinh, cosh, tanh :: a -> a
56 asinh, acosh, atanh :: a -> a
58 x ** y = exp (log x * y)
59 logBase x y = log y / log x
62 tanh x = sinh x / cosh x
64 -- | Efficient, machine-independent access to the components of a
65 -- floating-point number.
67 -- Minimal complete definition:
68 -- all except 'exponent', 'significand', 'scaleFloat' and 'atan2'
69 class (RealFrac a, Floating a) => RealFloat a where
70 -- | a constant function, returning the radix of the representation
72 floatRadix :: a -> Integer
73 -- | a constant function, returning the number of digits of
74 -- 'floatRadix' in the significand
75 floatDigits :: a -> Int
76 -- | a constant function, returning the lowest and highest values
77 -- the exponent may assume
78 floatRange :: a -> (Int,Int)
79 -- | The function 'decodeFloat' applied to a real floating-point
80 -- number returns the significand expressed as an 'Integer' and an
81 -- appropriately scaled exponent (an 'Int'). If @'decodeFloat' x@
82 -- yields @(m,n)@, then @x@ is equal in value to @m*b^^n@, where @b@
83 -- is the floating-point radix, and furthermore, either @m@ and @n@
84 -- are both zero or else @b^(d-1) <= m < b^d@, where @d@ is the value
85 -- of @'floatDigits' x@. In particular, @'decodeFloat' 0 = (0,0)@.
86 decodeFloat :: a -> (Integer,Int)
87 -- | 'encodeFloat' performs the inverse of 'decodeFloat'
88 encodeFloat :: Integer -> Int -> a
89 -- | the second component of 'decodeFloat'.
91 -- | the first component of 'decodeFloat', scaled to lie in the open
92 -- interval (@-1@,@1@)
94 -- | multiplies a floating-point number by an integer power of the radix
95 scaleFloat :: Int -> a -> a
96 -- | 'True' if the argument is an IEEE \"not-a-number\" (NaN) value
98 -- | 'True' if the argument is an IEEE infinity or negative infinity
99 isInfinite :: a -> Bool
100 -- | 'True' if the argument is too small to be represented in
102 isDenormalized :: a -> Bool
103 -- | 'True' if the argument is an IEEE negative zero
104 isNegativeZero :: a -> Bool
105 -- | 'True' if the argument is an IEEE floating point number
107 -- | a version of arctangent taking two real floating-point arguments.
108 -- For real floating @x@ and @y@, @'atan2' y x@ computes the angle
109 -- (from the positive x-axis) of the vector from the origin to the
110 -- point @(x,y)@. @'atan2' y x@ returns a value in the range [@-pi@,
111 -- @pi@]. It follows the Common Lisp semantics for the origin when
112 -- signed zeroes are supported. @'atan2' y 1@, with @y@ in a type
113 -- that is 'RealFloat', should return the same value as @'atan' y@.
114 -- A default definition of 'atan2' is provided, but implementors
115 -- can provide a more accurate implementation.
119 exponent x = if m == 0 then 0 else n + floatDigits x
120 where (m,n) = decodeFloat x
122 significand x = encodeFloat m (negate (floatDigits x))
123 where (m,_) = decodeFloat x
125 scaleFloat k x = encodeFloat m (n+k)
126 where (m,n) = decodeFloat x
130 | x == 0 && y > 0 = pi/2
131 | x < 0 && y > 0 = pi + atan (y/x)
132 |(x <= 0 && y < 0) ||
133 (x < 0 && isNegativeZero y) ||
134 (isNegativeZero x && isNegativeZero y)
136 | y == 0 && (x < 0 || isNegativeZero x)
137 = pi -- must be after the previous test on zero y
138 | x==0 && y==0 = y -- must be after the other double zero tests
139 | otherwise = x + y -- x or y is a NaN, return a NaN (via +)
143 %*********************************************************
145 \subsection{Type @Float@}
147 %*********************************************************
150 instance Eq Float where
151 (F# x) == (F# y) = x `eqFloat#` y
153 instance Ord Float where
154 (F# x) `compare` (F# y) | x `ltFloat#` y = LT
155 | x `eqFloat#` y = EQ
158 (F# x) < (F# y) = x `ltFloat#` y
159 (F# x) <= (F# y) = x `leFloat#` y
160 (F# x) >= (F# y) = x `geFloat#` y
161 (F# x) > (F# y) = x `gtFloat#` y
163 instance Num Float where
164 (+) x y = plusFloat x y
165 (-) x y = minusFloat x y
166 negate x = negateFloat x
167 (*) x y = timesFloat x y
169 | otherwise = negateFloat x
170 signum x | x == 0.0 = 0
172 | otherwise = negate 1
174 {-# INLINE fromInteger #-}
175 fromInteger i = F# (floatFromInteger i)
177 instance Real Float where
178 toRational x = (m%1)*(b%1)^^n
179 where (m,n) = decodeFloat x
182 instance Fractional Float where
183 (/) x y = divideFloat x y
184 fromRational x = fromRat x
187 {-# RULES "truncate/Float->Int" truncate = float2Int #-}
188 instance RealFrac Float where
190 {-# SPECIALIZE properFraction :: Float -> (Int, Float) #-}
191 {-# SPECIALIZE round :: Float -> Int #-}
193 {-# SPECIALIZE properFraction :: Float -> (Integer, Float) #-}
194 {-# SPECIALIZE round :: Float -> Integer #-}
196 -- ceiling, floor, and truncate are all small
197 {-# INLINE ceiling #-}
199 {-# INLINE truncate #-}
202 = case (decodeFloat x) of { (m,n) ->
203 let b = floatRadix x in
205 (fromInteger m * fromInteger b ^ n, 0.0)
207 case (quotRem m (b^(negate n))) of { (w,r) ->
208 (fromInteger w, encodeFloat r n)
212 truncate x = case properFraction x of
215 round x = case properFraction x of
217 m = if r < 0.0 then n - 1 else n + 1
218 half_down = abs r - 0.5
220 case (compare half_down 0.0) of
222 EQ -> if even n then n else m
225 ceiling x = case properFraction x of
226 (n,r) -> if r > 0.0 then n + 1 else n
228 floor x = case properFraction x of
229 (n,r) -> if r < 0.0 then n - 1 else n
231 instance Floating Float where
232 pi = 3.141592653589793238
245 (**) x y = powerFloat x y
246 logBase x y = log y / log x
248 asinh x = log (x + sqrt (1.0+x*x))
249 acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
250 atanh x = log ((x+1.0) / sqrt (1.0-x*x))
252 instance RealFloat Float where
253 floatRadix _ = FLT_RADIX -- from float.h
254 floatDigits _ = FLT_MANT_DIG -- ditto
255 floatRange _ = (FLT_MIN_EXP, FLT_MAX_EXP) -- ditto
257 decodeFloat (F# f#) = case decodeFloatInteger f# of
258 (# i, e #) -> (i, I# e)
260 encodeFloat i (I# e) = F# (encodeFloatInteger i e)
262 exponent x = case decodeFloat x of
263 (m,n) -> if m == 0 then 0 else n + floatDigits x
265 significand x = case decodeFloat x of
266 (m,_) -> encodeFloat m (negate (floatDigits x))
268 scaleFloat k x = case decodeFloat x of
269 (m,n) -> encodeFloat m (n+k)
270 isNaN x = 0 /= isFloatNaN x
271 isInfinite x = 0 /= isFloatInfinite x
272 isDenormalized x = 0 /= isFloatDenormalized x
273 isNegativeZero x = 0 /= isFloatNegativeZero x
276 instance Show Float where
277 showsPrec x = showSignedFloat showFloat x
278 showList = showList__ (showsPrec 0)
281 %*********************************************************
283 \subsection{Type @Double@}
285 %*********************************************************
288 instance Eq Double where
289 (D# x) == (D# y) = x ==## y
291 instance Ord Double where
292 (D# x) `compare` (D# y) | x <## y = LT
296 (D# x) < (D# y) = x <## y
297 (D# x) <= (D# y) = x <=## y
298 (D# x) >= (D# y) = x >=## y
299 (D# x) > (D# y) = x >## y
301 instance Num Double where
302 (+) x y = plusDouble x y
303 (-) x y = minusDouble x y
304 negate x = negateDouble x
305 (*) x y = timesDouble x y
307 | otherwise = negateDouble x
308 signum x | x == 0.0 = 0
310 | otherwise = negate 1
312 {-# INLINE fromInteger #-}
313 fromInteger i = D# (doubleFromInteger i)
316 instance Real Double where
317 toRational x = (m%1)*(b%1)^^n
318 where (m,n) = decodeFloat x
321 instance Fractional Double where
322 (/) x y = divideDouble x y
323 fromRational x = fromRat x
326 instance Floating Double where
327 pi = 3.141592653589793238
330 sqrt x = sqrtDouble x
334 asin x = asinDouble x
335 acos x = acosDouble x
336 atan x = atanDouble x
337 sinh x = sinhDouble x
338 cosh x = coshDouble x
339 tanh x = tanhDouble x
340 (**) x y = powerDouble x y
341 logBase x y = log y / log x
343 asinh x = log (x + sqrt (1.0+x*x))
344 acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
345 atanh x = log ((x+1.0) / sqrt (1.0-x*x))
347 {-# RULES "truncate/Double->Int" truncate = double2Int #-}
348 instance RealFrac Double where
350 {-# SPECIALIZE properFraction :: Double -> (Int, Double) #-}
351 {-# SPECIALIZE round :: Double -> Int #-}
353 {-# SPECIALIZE properFraction :: Double -> (Integer, Double) #-}
354 {-# SPECIALIZE round :: Double -> Integer #-}
356 -- ceiling, floor, and truncate are all small
357 {-# INLINE ceiling #-}
359 {-# INLINE truncate #-}
362 = case (decodeFloat x) of { (m,n) ->
363 let b = floatRadix x in
365 (fromInteger m * fromInteger b ^ n, 0.0)
367 case (quotRem m (b^(negate n))) of { (w,r) ->
368 (fromInteger w, encodeFloat r n)
372 truncate x = case properFraction x of
375 round x = case properFraction x of
377 m = if r < 0.0 then n - 1 else n + 1
378 half_down = abs r - 0.5
380 case (compare half_down 0.0) of
382 EQ -> if even n then n else m
385 ceiling x = case properFraction x of
386 (n,r) -> if r > 0.0 then n + 1 else n
388 floor x = case properFraction x of
389 (n,r) -> if r < 0.0 then n - 1 else n
391 instance RealFloat Double where
392 floatRadix _ = FLT_RADIX -- from float.h
393 floatDigits _ = DBL_MANT_DIG -- ditto
394 floatRange _ = (DBL_MIN_EXP, DBL_MAX_EXP) -- ditto
397 = case decodeDoubleInteger x# of
398 (# i, j #) -> (i, I# j)
400 encodeFloat i (I# j) = D# (encodeDoubleInteger i j)
402 exponent x = case decodeFloat x of
403 (m,n) -> if m == 0 then 0 else n + floatDigits x
405 significand x = case decodeFloat x of
406 (m,_) -> encodeFloat m (negate (floatDigits x))
408 scaleFloat k x = case decodeFloat x of
409 (m,n) -> encodeFloat m (n+k)
411 isNaN x = 0 /= isDoubleNaN x
412 isInfinite x = 0 /= isDoubleInfinite x
413 isDenormalized x = 0 /= isDoubleDenormalized x
414 isNegativeZero x = 0 /= isDoubleNegativeZero x
417 instance Show Double where
418 showsPrec x = showSignedFloat showFloat x
419 showList = showList__ (showsPrec 0)
422 %*********************************************************
424 \subsection{@Enum@ instances}
426 %*********************************************************
428 The @Enum@ instances for Floats and Doubles are slightly unusual.
429 The @toEnum@ function truncates numbers to Int. The definitions
430 of @enumFrom@ and @enumFromThen@ allow floats to be used in arithmetic
431 series: [0,0.1 .. 1.0]. However, roundoff errors make these somewhat
432 dubious. This example may have either 10 or 11 elements, depending on
433 how 0.1 is represented.
435 NOTE: The instances for Float and Double do not make use of the default
436 methods for @enumFromTo@ and @enumFromThenTo@, as these rely on there being
437 a `non-lossy' conversion to and from Ints. Instead we make use of the
438 1.2 default methods (back in the days when Enum had Ord as a superclass)
439 for these (@numericEnumFromTo@ and @numericEnumFromThenTo@ below.)
442 instance Enum Float where
446 fromEnum = fromInteger . truncate -- may overflow
447 enumFrom = numericEnumFrom
448 enumFromTo = numericEnumFromTo
449 enumFromThen = numericEnumFromThen
450 enumFromThenTo = numericEnumFromThenTo
452 instance Enum Double where
456 fromEnum = fromInteger . truncate -- may overflow
457 enumFrom = numericEnumFrom
458 enumFromTo = numericEnumFromTo
459 enumFromThen = numericEnumFromThen
460 enumFromThenTo = numericEnumFromThenTo
464 %*********************************************************
466 \subsection{Printing floating point}
468 %*********************************************************
472 -- | Show a signed 'RealFloat' value to full precision
473 -- using standard decimal notation for arguments whose absolute value lies
474 -- between @0.1@ and @9,999,999@, and scientific notation otherwise.
475 showFloat :: (RealFloat a) => a -> ShowS
476 showFloat x = showString (formatRealFloat FFGeneric Nothing x)
478 -- These are the format types. This type is not exported.
480 data FFFormat = FFExponent | FFFixed | FFGeneric
482 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
483 formatRealFloat fmt decs x
485 | isInfinite x = if x < 0 then "-Infinity" else "Infinity"
486 | x < 0 || isNegativeZero x = '-':doFmt fmt (floatToDigits (toInteger base) (-x))
487 | otherwise = doFmt fmt (floatToDigits (toInteger base) x)
491 doFmt format (is, e) =
492 let ds = map intToDigit is in
495 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
500 let show_e' = show (e-1) in
503 [d] -> d : ".0e" ++ show_e'
504 (d:ds') -> d : '.' : ds' ++ "e" ++ show_e'
505 [] -> error "formatRealFloat/doFmt/FFExponent: []"
507 let dec' = max dec 1 in
509 [0] -> '0' :'.' : take dec' (repeat '0') ++ "e0"
512 (ei,is') = roundTo base (dec'+1) is
513 (d:ds') = map intToDigit (if ei > 0 then init is' else is')
515 d:'.':ds' ++ 'e':show (e-1+ei)
518 mk0 ls = case ls of { "" -> "0" ; _ -> ls}
522 | e <= 0 -> "0." ++ replicate (-e) '0' ++ ds
525 f 0 s rs = mk0 (reverse s) ++ '.':mk0 rs
526 f n s "" = f (n-1) ('0':s) ""
527 f n s (r:rs) = f (n-1) (r:s) rs
531 let dec' = max dec 0 in
534 (ei,is') = roundTo base (dec' + e) is
535 (ls,rs) = splitAt (e+ei) (map intToDigit is')
537 mk0 ls ++ (if null rs then "" else '.':rs)
540 (ei,is') = roundTo base dec' (replicate (-e) 0 ++ is)
541 d:ds' = map intToDigit (if ei > 0 then is' else 0:is')
543 d : (if null ds' then "" else '.':ds')
546 roundTo :: Int -> Int -> [Int] -> (Int,[Int])
551 _ -> error "roundTo: bad Value"
555 f n [] = (0, replicate n 0)
556 f 0 (x:_) = (if x >= b2 then 1 else 0, [])
558 | i' == base = (1,0:ds)
559 | otherwise = (0,i':ds)
564 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
565 -- by R.G. Burger and R.K. Dybvig in PLDI 96.
566 -- This version uses a much slower logarithm estimator. It should be improved.
568 -- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,
569 -- and returns a list of digits and an exponent.
570 -- In particular, if @x>=0@, and
572 -- > floatToDigits base x = ([d1,d2,...,dn], e)
578 -- (2) @x = 0.d1d2...dn * (base**e)@
580 -- (3) @0 <= di <= base-1@
582 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
583 floatToDigits _ 0 = ([0], 0)
584 floatToDigits base x =
586 (f0, e0) = decodeFloat x
587 (minExp0, _) = floatRange x
590 minExp = minExp0 - p -- the real minimum exponent
591 -- Haskell requires that f be adjusted so denormalized numbers
592 -- will have an impossibly low exponent. Adjust for this.
594 let n = minExp - e0 in
595 if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
600 (f*be*b*2, 2*b, be*b, b)
604 if e > minExp && f == b^(p-1) then
605 (f*b*2, b^(-e+1)*2, b, 1)
607 (f*2, b^(-e)*2, 1, 1)
613 if b == 2 && base == 10 then
614 -- logBase 10 2 is slightly bigger than 3/10 so
615 -- the following will err on the low side. Ignoring
616 -- the fraction will make it err even more.
617 -- Haskell promises that p-1 <= logBase b f < p.
618 (p - 1 + e0) * 3 `div` 10
620 ceiling ((log (fromInteger (f+1)) +
621 fromIntegral e * log (fromInteger b)) /
622 log (fromInteger base))
623 --WAS: fromInt e * log (fromInteger b))
627 if r + mUp <= expt base n * s then n else fixup (n+1)
629 if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)
633 gen ds rn sN mUpN mDnN =
635 (dn, rn') = (rn * base) `divMod` sN
639 case (rn' < mDnN', rn' + mUpN' > sN) of
640 (True, False) -> dn : ds
641 (False, True) -> dn+1 : ds
642 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
643 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
647 gen [] r (s * expt base k) mUp mDn
649 let bk = expt base (-k) in
650 gen [] (r * bk) s (mUp * bk) (mDn * bk)
652 (map fromIntegral (reverse rds), k)
657 %*********************************************************
659 \subsection{Converting from a Rational to a RealFloat
661 %*********************************************************
663 [In response to a request for documentation of how fromRational works,
664 Joe Fasel writes:] A quite reasonable request! This code was added to
665 the Prelude just before the 1.2 release, when Lennart, working with an
666 early version of hbi, noticed that (read . show) was not the identity
667 for floating-point numbers. (There was a one-bit error about half the
668 time.) The original version of the conversion function was in fact
669 simply a floating-point divide, as you suggest above. The new version
670 is, I grant you, somewhat denser.
672 Unfortunately, Joe's code doesn't work! Here's an example:
674 main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")
679 1.8217369128763981e-300
684 fromRat :: (RealFloat a) => Rational -> a
688 -- If the exponent of the nearest floating-point number to x
689 -- is e, then the significand is the integer nearest xb^(-e),
690 -- where b is the floating-point radix. We start with a good
691 -- guess for e, and if it is correct, the exponent of the
692 -- floating-point number we construct will again be e. If
693 -- not, one more iteration is needed.
695 f e = if e' == e then y else f e'
696 where y = encodeFloat (round (x * (1 % b)^^e)) e
697 (_,e') = decodeFloat y
700 -- We obtain a trial exponent by doing a floating-point
701 -- division of x's numerator by its denominator. The
702 -- result of this division may not itself be the ultimate
703 -- result, because of an accumulation of three rounding
706 (s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
707 / fromInteger (denominator x))
710 Now, here's Lennart's code (which works)
713 -- | Converts a 'Rational' value into any type in class 'RealFloat'.
714 {-# SPECIALISE fromRat :: Rational -> Double,
715 Rational -> Float #-}
716 fromRat :: (RealFloat a) => Rational -> a
718 -- Deal with special cases first, delegating the real work to fromRat'
719 fromRat (n :% 0) | n > 0 = 1/0 -- +Infinity
720 | n < 0 = -1/0 -- -Infinity
721 | otherwise = 0/0 -- NaN
723 fromRat (n :% d) | n > 0 = fromRat' (n :% d)
724 | n < 0 = - fromRat' ((-n) :% d)
725 | otherwise = encodeFloat 0 0 -- Zero
727 -- Conversion process:
728 -- Scale the rational number by the RealFloat base until
729 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
730 -- Then round the rational to an Integer and encode it with the exponent
731 -- that we got from the scaling.
732 -- To speed up the scaling process we compute the log2 of the number to get
733 -- a first guess of the exponent.
735 fromRat' :: (RealFloat a) => Rational -> a
736 -- Invariant: argument is strictly positive
738 where b = floatRadix r
740 (minExp0, _) = floatRange r
741 minExp = minExp0 - p -- the real minimum exponent
742 xMin = toRational (expt b (p-1))
743 xMax = toRational (expt b p)
744 p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp
745 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
746 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
747 r = encodeFloat (round x') p'
749 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
750 scaleRat :: Rational -> Int -> Rational -> Rational -> Int -> Rational -> (Rational, Int)
751 scaleRat b minExp xMin xMax p x
752 | p <= minExp = (x, p)
753 | x >= xMax = scaleRat b minExp xMin xMax (p+1) (x/b)
754 | x < xMin = scaleRat b minExp xMin xMax (p-1) (x*b)
757 -- Exponentiation with a cache for the most common numbers.
758 minExpt, maxExpt :: Int
762 expt :: Integer -> Int -> Integer
764 if base == 2 && n >= minExpt && n <= maxExpt then
769 expts :: Array Int Integer
770 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
772 -- Compute the (floor of the) log of i in base b.
773 -- Simplest way would be just divide i by b until it's smaller then b, but that would
774 -- be very slow! We are just slightly more clever.
775 integerLogBase :: Integer -> Integer -> Int
778 | otherwise = doDiv (i `div` (b^l)) l
780 -- Try squaring the base first to cut down the number of divisions.
781 l = 2 * integerLogBase (b*b) i
783 doDiv :: Integer -> Int -> Int
786 | otherwise = doDiv (x `div` b) (y+1)
791 %*********************************************************
793 \subsection{Floating point numeric primops}
795 %*********************************************************
797 Definitions of the boxed PrimOps; these will be
798 used in the case of partial applications, etc.
801 plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float
802 plusFloat (F# x) (F# y) = F# (plusFloat# x y)
803 minusFloat (F# x) (F# y) = F# (minusFloat# x y)
804 timesFloat (F# x) (F# y) = F# (timesFloat# x y)
805 divideFloat (F# x) (F# y) = F# (divideFloat# x y)
807 negateFloat :: Float -> Float
808 negateFloat (F# x) = F# (negateFloat# x)
810 gtFloat, geFloat, eqFloat, neFloat, ltFloat, leFloat :: Float -> Float -> Bool
811 gtFloat (F# x) (F# y) = gtFloat# x y
812 geFloat (F# x) (F# y) = geFloat# x y
813 eqFloat (F# x) (F# y) = eqFloat# x y
814 neFloat (F# x) (F# y) = neFloat# x y
815 ltFloat (F# x) (F# y) = ltFloat# x y
816 leFloat (F# x) (F# y) = leFloat# x y
818 float2Int :: Float -> Int
819 float2Int (F# x) = I# (float2Int# x)
821 int2Float :: Int -> Float
822 int2Float (I# x) = F# (int2Float# x)
824 expFloat, logFloat, sqrtFloat :: Float -> Float
825 sinFloat, cosFloat, tanFloat :: Float -> Float
826 asinFloat, acosFloat, atanFloat :: Float -> Float
827 sinhFloat, coshFloat, tanhFloat :: Float -> Float
828 expFloat (F# x) = F# (expFloat# x)
829 logFloat (F# x) = F# (logFloat# x)
830 sqrtFloat (F# x) = F# (sqrtFloat# x)
831 sinFloat (F# x) = F# (sinFloat# x)
832 cosFloat (F# x) = F# (cosFloat# x)
833 tanFloat (F# x) = F# (tanFloat# x)
834 asinFloat (F# x) = F# (asinFloat# x)
835 acosFloat (F# x) = F# (acosFloat# x)
836 atanFloat (F# x) = F# (atanFloat# x)
837 sinhFloat (F# x) = F# (sinhFloat# x)
838 coshFloat (F# x) = F# (coshFloat# x)
839 tanhFloat (F# x) = F# (tanhFloat# x)
841 powerFloat :: Float -> Float -> Float
842 powerFloat (F# x) (F# y) = F# (powerFloat# x y)
844 -- definitions of the boxed PrimOps; these will be
845 -- used in the case of partial applications, etc.
847 plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double
848 plusDouble (D# x) (D# y) = D# (x +## y)
849 minusDouble (D# x) (D# y) = D# (x -## y)
850 timesDouble (D# x) (D# y) = D# (x *## y)
851 divideDouble (D# x) (D# y) = D# (x /## y)
853 negateDouble :: Double -> Double
854 negateDouble (D# x) = D# (negateDouble# x)
856 gtDouble, geDouble, eqDouble, neDouble, leDouble, ltDouble :: Double -> Double -> Bool
857 gtDouble (D# x) (D# y) = x >## y
858 geDouble (D# x) (D# y) = x >=## y
859 eqDouble (D# x) (D# y) = x ==## y
860 neDouble (D# x) (D# y) = x /=## y
861 ltDouble (D# x) (D# y) = x <## y
862 leDouble (D# x) (D# y) = x <=## y
864 double2Int :: Double -> Int
865 double2Int (D# x) = I# (double2Int# x)
867 int2Double :: Int -> Double
868 int2Double (I# x) = D# (int2Double# x)
870 double2Float :: Double -> Float
871 double2Float (D# x) = F# (double2Float# x)
873 float2Double :: Float -> Double
874 float2Double (F# x) = D# (float2Double# x)
876 expDouble, logDouble, sqrtDouble :: Double -> Double
877 sinDouble, cosDouble, tanDouble :: Double -> Double
878 asinDouble, acosDouble, atanDouble :: Double -> Double
879 sinhDouble, coshDouble, tanhDouble :: Double -> Double
880 expDouble (D# x) = D# (expDouble# x)
881 logDouble (D# x) = D# (logDouble# x)
882 sqrtDouble (D# x) = D# (sqrtDouble# x)
883 sinDouble (D# x) = D# (sinDouble# x)
884 cosDouble (D# x) = D# (cosDouble# x)
885 tanDouble (D# x) = D# (tanDouble# x)
886 asinDouble (D# x) = D# (asinDouble# x)
887 acosDouble (D# x) = D# (acosDouble# x)
888 atanDouble (D# x) = D# (atanDouble# x)
889 sinhDouble (D# x) = D# (sinhDouble# x)
890 coshDouble (D# x) = D# (coshDouble# x)
891 tanhDouble (D# x) = D# (tanhDouble# x)
893 powerDouble :: Double -> Double -> Double
894 powerDouble (D# x) (D# y) = D# (x **## y)
898 foreign import ccall unsafe "__encodeFloat"
899 encodeFloat# :: Int# -> ByteArray# -> Int -> Float
900 foreign import ccall unsafe "__int_encodeFloat"
901 int_encodeFloat# :: Int# -> Int -> Float
904 foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int
905 foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int
906 foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int
907 foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int
910 foreign import ccall unsafe "__encodeDouble"
911 encodeDouble# :: Int# -> ByteArray# -> Int -> Double
913 foreign import ccall unsafe "isDoubleNaN" isDoubleNaN :: Double -> Int
914 foreign import ccall unsafe "isDoubleInfinite" isDoubleInfinite :: Double -> Int
915 foreign import ccall unsafe "isDoubleDenormalized" isDoubleDenormalized :: Double -> Int
916 foreign import ccall unsafe "isDoubleNegativeZero" isDoubleNegativeZero :: Double -> Int
919 %*********************************************************
921 \subsection{Coercion rules}
923 %*********************************************************
927 "fromIntegral/Int->Float" fromIntegral = int2Float
928 "fromIntegral/Int->Double" fromIntegral = int2Double
929 "realToFrac/Float->Float" realToFrac = id :: Float -> Float
930 "realToFrac/Float->Double" realToFrac = float2Double
931 "realToFrac/Double->Float" realToFrac = double2Float
932 "realToFrac/Double->Double" realToFrac = id :: Double -> Double
933 "realToFrac/Int->Double" realToFrac = int2Double -- See Note [realToFrac int-to-float]
934 "realToFrac/Int->Float" realToFrac = int2Float -- ..ditto
938 Note [realToFrac int-to-float]
939 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
940 Don found that the RULES for realToFrac/Int->Double and simliarly
941 Float made a huge difference to some stream-fusion programs. Here's
944 import Data.Array.Vector
949 let c = replicateU n (2::Double)
950 a = mapU realToFrac (enumFromToU 0 (n-1) ) :: UArr Double
951 print (sumU (zipWithU (*) c a))
953 Without the RULE we get this loop body:
955 case $wtoRational sc_sY4 of ww_aM7 { (# ww1_aM9, ww2_aMa #) ->
956 case $wfromRat ww1_aM9 ww2_aMa of tpl_X1P { D# ipv_sW3 ->
960 (+## sc2_sY6 (*## 2.0 ipv_sW3))
967 (+## sc2_sXV (*## 2.0 (int2Double# sc_sXT)))
969 The running time of the program goes from 120 seconds to 0.198 seconds
970 with the native backend, and 0.143 seconds with the C backend.
972 A few more details in Trac #2251, and the patch message
973 "Add RULES for realToFrac from Int".
975 %*********************************************************
979 %*********************************************************
982 showSignedFloat :: (RealFloat a)
983 => (a -> ShowS) -- ^ a function that can show unsigned values
984 -> Int -- ^ the precedence of the enclosing context
985 -> a -- ^ the value to show
987 showSignedFloat showPos p x
988 | x < 0 || isNegativeZero x
989 = showParen (p > 6) (showChar '-' . showPos (-x))
990 | otherwise = showPos x