2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_GHC -fno-warn-orphans #-}
4 {-# OPTIONS_HADDOCK hide #-}
5 -----------------------------------------------------------------------------
8 -- Copyright : (c) The University of Glasgow 1994-2002
9 -- License : see libraries/base/LICENSE
11 -- Maintainer : cvs-ghc@haskell.org
12 -- Stability : internal
13 -- Portability : non-portable (GHC Extensions)
15 -- The types 'Float' and 'Double', and the classes 'Floating' and 'RealFloat'.
17 -----------------------------------------------------------------------------
19 #include "ieee-flpt.h"
22 module GHC.Float( module GHC.Float, Float(..), Double(..), Float#, Double# )
39 %*********************************************************
41 \subsection{Standard numeric classes}
43 %*********************************************************
46 -- | Trigonometric and hyperbolic functions and related functions.
48 -- Minimal complete definition:
49 -- 'pi', 'exp', 'log', 'sin', 'cos', 'sinh', 'cosh',
50 -- 'asin', 'acos', 'atan', 'asinh', 'acosh' and 'atanh'
51 class (Fractional a) => Floating a where
53 exp, log, sqrt :: a -> a
54 (**), logBase :: a -> a -> a
55 sin, cos, tan :: a -> a
56 asin, acos, atan :: a -> a
57 sinh, cosh, tanh :: a -> a
58 asinh, acosh, atanh :: a -> a
60 x ** y = exp (log x * y)
61 logBase x y = log y / log x
64 tanh x = sinh x / cosh x
66 -- | Efficient, machine-independent access to the components of a
67 -- floating-point number.
69 -- Minimal complete definition:
70 -- all except 'exponent', 'significand', 'scaleFloat' and 'atan2'
71 class (RealFrac a, Floating a) => RealFloat a where
72 -- | a constant function, returning the radix of the representation
74 floatRadix :: a -> Integer
75 -- | a constant function, returning the number of digits of
76 -- 'floatRadix' in the significand
77 floatDigits :: a -> Int
78 -- | a constant function, returning the lowest and highest values
79 -- the exponent may assume
80 floatRange :: a -> (Int,Int)
81 -- | The function 'decodeFloat' applied to a real floating-point
82 -- number returns the significand expressed as an 'Integer' and an
83 -- appropriately scaled exponent (an 'Int'). If @'decodeFloat' x@
84 -- yields @(m,n)@, then @x@ is equal in value to @m*b^^n@, where @b@
85 -- is the floating-point radix, and furthermore, either @m@ and @n@
86 -- are both zero or else @b^(d-1) <= m < b^d@, where @d@ is the value
87 -- of @'floatDigits' x@. In particular, @'decodeFloat' 0 = (0,0)@.
88 decodeFloat :: a -> (Integer,Int)
89 -- | 'encodeFloat' performs the inverse of 'decodeFloat'
90 encodeFloat :: Integer -> Int -> a
91 -- | the second component of 'decodeFloat'.
93 -- | the first component of 'decodeFloat', scaled to lie in the open
94 -- interval (@-1@,@1@)
96 -- | multiplies a floating-point number by an integer power of the radix
97 scaleFloat :: Int -> a -> a
98 -- | 'True' if the argument is an IEEE \"not-a-number\" (NaN) value
100 -- | 'True' if the argument is an IEEE infinity or negative infinity
101 isInfinite :: a -> Bool
102 -- | 'True' if the argument is too small to be represented in
104 isDenormalized :: a -> Bool
105 -- | 'True' if the argument is an IEEE negative zero
106 isNegativeZero :: a -> Bool
107 -- | 'True' if the argument is an IEEE floating point number
109 -- | a version of arctangent taking two real floating-point arguments.
110 -- For real floating @x@ and @y@, @'atan2' y x@ computes the angle
111 -- (from the positive x-axis) of the vector from the origin to the
112 -- point @(x,y)@. @'atan2' y x@ returns a value in the range [@-pi@,
113 -- @pi@]. It follows the Common Lisp semantics for the origin when
114 -- signed zeroes are supported. @'atan2' y 1@, with @y@ in a type
115 -- that is 'RealFloat', should return the same value as @'atan' y@.
116 -- A default definition of 'atan2' is provided, but implementors
117 -- can provide a more accurate implementation.
121 exponent x = if m == 0 then 0 else n + floatDigits x
122 where (m,n) = decodeFloat x
124 significand x = encodeFloat m (negate (floatDigits x))
125 where (m,_) = decodeFloat x
127 scaleFloat k x = encodeFloat m (n+k)
128 where (m,n) = decodeFloat x
132 | x == 0 && y > 0 = pi/2
133 | x < 0 && y > 0 = pi + atan (y/x)
134 |(x <= 0 && y < 0) ||
135 (x < 0 && isNegativeZero y) ||
136 (isNegativeZero x && isNegativeZero y)
138 | y == 0 && (x < 0 || isNegativeZero x)
139 = pi -- must be after the previous test on zero y
140 | x==0 && y==0 = y -- must be after the other double zero tests
141 | otherwise = x + y -- x or y is a NaN, return a NaN (via +)
145 %*********************************************************
147 \subsection{Type @Float@}
149 %*********************************************************
152 instance Eq Float where
153 (F# x) == (F# y) = x `eqFloat#` y
155 instance Ord Float where
156 (F# x) `compare` (F# y) | x `ltFloat#` y = LT
157 | x `eqFloat#` y = EQ
160 (F# x) < (F# y) = x `ltFloat#` y
161 (F# x) <= (F# y) = x `leFloat#` y
162 (F# x) >= (F# y) = x `geFloat#` y
163 (F# x) > (F# y) = x `gtFloat#` y
165 instance Num Float where
166 (+) x y = plusFloat x y
167 (-) x y = minusFloat x y
168 negate x = negateFloat x
169 (*) x y = timesFloat x y
171 | otherwise = negateFloat x
172 signum x | x == 0.0 = 0
174 | otherwise = negate 1
176 {-# INLINE fromInteger #-}
177 fromInteger i = F# (floatFromInteger i)
179 instance Real Float where
180 toRational x = (m%1)*(b%1)^^n
181 where (m,n) = decodeFloat x
184 instance Fractional Float where
185 (/) x y = divideFloat x y
186 fromRational x = fromRat x
189 {-# RULES "truncate/Float->Int" truncate = float2Int #-}
190 instance RealFrac Float where
192 {-# SPECIALIZE properFraction :: Float -> (Int, Float) #-}
193 {-# SPECIALIZE round :: Float -> Int #-}
195 {-# SPECIALIZE properFraction :: Float -> (Integer, Float) #-}
196 {-# SPECIALIZE round :: Float -> Integer #-}
198 -- ceiling, floor, and truncate are all small
199 {-# INLINE ceiling #-}
201 {-# INLINE truncate #-}
203 -- We assume that FLT_RADIX is 2 so that we can use more efficient code
205 #error FLT_RADIX must be 2
207 properFraction (F# x#)
208 = case (decodeFloat_Int# x#) of
214 then (fromIntegral m * (2 ^ n), 0.0)
215 else let i = if m >= 0 then m `shiftR` negate n
216 else negate (negate m `shiftR` negate n)
217 f = m - (i `shiftL` negate n)
218 in (fromIntegral i, encodeFloat (fromIntegral f) n)
220 truncate x = case properFraction x of
223 round x = case properFraction x of
225 m = if r < 0.0 then n - 1 else n + 1
226 half_down = abs r - 0.5
228 case (compare half_down 0.0) of
230 EQ -> if even n then n else m
233 ceiling x = case properFraction x of
234 (n,r) -> if r > 0.0 then n + 1 else n
236 floor x = case properFraction x of
237 (n,r) -> if r < 0.0 then n - 1 else n
239 instance Floating Float where
240 pi = 3.141592653589793238
253 (**) x y = powerFloat x y
254 logBase x y = log y / log x
256 asinh x = log (x + sqrt (1.0+x*x))
257 acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
258 atanh x = log ((x+1.0) / sqrt (1.0-x*x))
260 instance RealFloat Float where
261 floatRadix _ = FLT_RADIX -- from float.h
262 floatDigits _ = FLT_MANT_DIG -- ditto
263 floatRange _ = (FLT_MIN_EXP, FLT_MAX_EXP) -- ditto
265 decodeFloat (F# f#) = case decodeFloat_Int# f# of
266 (# i, e #) -> (smallInteger i, I# e)
268 encodeFloat i (I# e) = F# (encodeFloatInteger i e)
270 exponent x = case decodeFloat x of
271 (m,n) -> if m == 0 then 0 else n + floatDigits x
273 significand x = case decodeFloat x of
274 (m,_) -> encodeFloat m (negate (floatDigits x))
276 scaleFloat k x = case decodeFloat x of
277 (m,n) -> encodeFloat m (n+k)
278 isNaN x = 0 /= isFloatNaN x
279 isInfinite x = 0 /= isFloatInfinite x
280 isDenormalized x = 0 /= isFloatDenormalized x
281 isNegativeZero x = 0 /= isFloatNegativeZero x
284 instance Show Float where
285 showsPrec x = showSignedFloat showFloat x
286 showList = showList__ (showsPrec 0)
289 %*********************************************************
291 \subsection{Type @Double@}
293 %*********************************************************
296 instance Eq Double where
297 (D# x) == (D# y) = x ==## y
299 instance Ord Double where
300 (D# x) `compare` (D# y) | x <## y = LT
304 (D# x) < (D# y) = x <## y
305 (D# x) <= (D# y) = x <=## y
306 (D# x) >= (D# y) = x >=## y
307 (D# x) > (D# y) = x >## y
309 instance Num Double where
310 (+) x y = plusDouble x y
311 (-) x y = minusDouble x y
312 negate x = negateDouble x
313 (*) x y = timesDouble x y
315 | otherwise = negateDouble x
316 signum x | x == 0.0 = 0
318 | otherwise = negate 1
320 {-# INLINE fromInteger #-}
321 fromInteger i = D# (doubleFromInteger i)
324 instance Real Double where
325 toRational x = (m%1)*(b%1)^^n
326 where (m,n) = decodeFloat x
329 instance Fractional Double where
330 (/) x y = divideDouble x y
331 fromRational x = fromRat x
334 instance Floating Double where
335 pi = 3.141592653589793238
338 sqrt x = sqrtDouble x
342 asin x = asinDouble x
343 acos x = acosDouble x
344 atan x = atanDouble x
345 sinh x = sinhDouble x
346 cosh x = coshDouble x
347 tanh x = tanhDouble x
348 (**) x y = powerDouble x y
349 logBase x y = log y / log x
351 asinh x = log (x + sqrt (1.0+x*x))
352 acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
353 atanh x = log ((x+1.0) / sqrt (1.0-x*x))
355 {-# RULES "truncate/Double->Int" truncate = double2Int #-}
356 instance RealFrac Double where
358 {-# SPECIALIZE properFraction :: Double -> (Int, Double) #-}
359 {-# SPECIALIZE round :: Double -> Int #-}
361 {-# SPECIALIZE properFraction :: Double -> (Integer, Double) #-}
362 {-# SPECIALIZE round :: Double -> Integer #-}
364 -- ceiling, floor, and truncate are all small
365 {-# INLINE ceiling #-}
367 {-# INLINE truncate #-}
370 = case (decodeFloat x) of { (m,n) ->
371 let b = floatRadix x in
373 (fromInteger m * fromInteger b ^ n, 0.0)
375 case (quotRem m (b^(negate n))) of { (w,r) ->
376 (fromInteger w, encodeFloat r n)
380 truncate x = case properFraction x of
383 round x = case properFraction x of
385 m = if r < 0.0 then n - 1 else n + 1
386 half_down = abs r - 0.5
388 case (compare half_down 0.0) of
390 EQ -> if even n then n else m
393 ceiling x = case properFraction x of
394 (n,r) -> if r > 0.0 then n + 1 else n
396 floor x = case properFraction x of
397 (n,r) -> if r < 0.0 then n - 1 else n
399 instance RealFloat Double where
400 floatRadix _ = FLT_RADIX -- from float.h
401 floatDigits _ = DBL_MANT_DIG -- ditto
402 floatRange _ = (DBL_MIN_EXP, DBL_MAX_EXP) -- ditto
405 = case decodeDoubleInteger x# of
406 (# i, j #) -> (i, I# j)
408 encodeFloat i (I# j) = D# (encodeDoubleInteger i j)
410 exponent x = case decodeFloat x of
411 (m,n) -> if m == 0 then 0 else n + floatDigits x
413 significand x = case decodeFloat x of
414 (m,_) -> encodeFloat m (negate (floatDigits x))
416 scaleFloat k x = case decodeFloat x of
417 (m,n) -> encodeFloat m (n+k)
419 isNaN x = 0 /= isDoubleNaN x
420 isInfinite x = 0 /= isDoubleInfinite x
421 isDenormalized x = 0 /= isDoubleDenormalized x
422 isNegativeZero x = 0 /= isDoubleNegativeZero x
425 instance Show Double where
426 showsPrec x = showSignedFloat showFloat x
427 showList = showList__ (showsPrec 0)
430 %*********************************************************
432 \subsection{@Enum@ instances}
434 %*********************************************************
436 The @Enum@ instances for Floats and Doubles are slightly unusual.
437 The @toEnum@ function truncates numbers to Int. The definitions
438 of @enumFrom@ and @enumFromThen@ allow floats to be used in arithmetic
439 series: [0,0.1 .. 1.0]. However, roundoff errors make these somewhat
440 dubious. This example may have either 10 or 11 elements, depending on
441 how 0.1 is represented.
443 NOTE: The instances for Float and Double do not make use of the default
444 methods for @enumFromTo@ and @enumFromThenTo@, as these rely on there being
445 a `non-lossy' conversion to and from Ints. Instead we make use of the
446 1.2 default methods (back in the days when Enum had Ord as a superclass)
447 for these (@numericEnumFromTo@ and @numericEnumFromThenTo@ below.)
450 instance Enum Float where
454 fromEnum = fromInteger . truncate -- may overflow
455 enumFrom = numericEnumFrom
456 enumFromTo = numericEnumFromTo
457 enumFromThen = numericEnumFromThen
458 enumFromThenTo = numericEnumFromThenTo
460 instance Enum Double where
464 fromEnum = fromInteger . truncate -- may overflow
465 enumFrom = numericEnumFrom
466 enumFromTo = numericEnumFromTo
467 enumFromThen = numericEnumFromThen
468 enumFromThenTo = numericEnumFromThenTo
472 %*********************************************************
474 \subsection{Printing floating point}
476 %*********************************************************
480 -- | Show a signed 'RealFloat' value to full precision
481 -- using standard decimal notation for arguments whose absolute value lies
482 -- between @0.1@ and @9,999,999@, and scientific notation otherwise.
483 showFloat :: (RealFloat a) => a -> ShowS
484 showFloat x = showString (formatRealFloat FFGeneric Nothing x)
486 -- These are the format types. This type is not exported.
488 data FFFormat = FFExponent | FFFixed | FFGeneric
490 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
491 formatRealFloat fmt decs x
493 | isInfinite x = if x < 0 then "-Infinity" else "Infinity"
494 | x < 0 || isNegativeZero x = '-':doFmt fmt (floatToDigits (toInteger base) (-x))
495 | otherwise = doFmt fmt (floatToDigits (toInteger base) x)
499 doFmt format (is, e) =
500 let ds = map intToDigit is in
503 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
508 let show_e' = show (e-1) in
511 [d] -> d : ".0e" ++ show_e'
512 (d:ds') -> d : '.' : ds' ++ "e" ++ show_e'
513 [] -> error "formatRealFloat/doFmt/FFExponent: []"
515 let dec' = max dec 1 in
517 [0] -> '0' :'.' : take dec' (repeat '0') ++ "e0"
520 (ei,is') = roundTo base (dec'+1) is
521 (d:ds') = map intToDigit (if ei > 0 then init is' else is')
523 d:'.':ds' ++ 'e':show (e-1+ei)
526 mk0 ls = case ls of { "" -> "0" ; _ -> ls}
530 | e <= 0 -> "0." ++ replicate (-e) '0' ++ ds
533 f 0 s rs = mk0 (reverse s) ++ '.':mk0 rs
534 f n s "" = f (n-1) ('0':s) ""
535 f n s (r:rs) = f (n-1) (r:s) rs
539 let dec' = max dec 0 in
542 (ei,is') = roundTo base (dec' + e) is
543 (ls,rs) = splitAt (e+ei) (map intToDigit is')
545 mk0 ls ++ (if null rs then "" else '.':rs)
548 (ei,is') = roundTo base dec' (replicate (-e) 0 ++ is)
549 d:ds' = map intToDigit (if ei > 0 then is' else 0:is')
551 d : (if null ds' then "" else '.':ds')
554 roundTo :: Int -> Int -> [Int] -> (Int,[Int])
559 _ -> error "roundTo: bad Value"
563 f n [] = (0, replicate n 0)
564 f 0 (x:_) = (if x >= b2 then 1 else 0, [])
566 | i' == base = (1,0:ds)
567 | otherwise = (0,i':ds)
572 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
573 -- by R.G. Burger and R.K. Dybvig in PLDI 96.
574 -- This version uses a much slower logarithm estimator. It should be improved.
576 -- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,
577 -- and returns a list of digits and an exponent.
578 -- In particular, if @x>=0@, and
580 -- > floatToDigits base x = ([d1,d2,...,dn], e)
586 -- (2) @x = 0.d1d2...dn * (base**e)@
588 -- (3) @0 <= di <= base-1@
590 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
591 floatToDigits _ 0 = ([0], 0)
592 floatToDigits base x =
594 (f0, e0) = decodeFloat x
595 (minExp0, _) = floatRange x
598 minExp = minExp0 - p -- the real minimum exponent
599 -- Haskell requires that f be adjusted so denormalized numbers
600 -- will have an impossibly low exponent. Adjust for this.
602 let n = minExp - e0 in
603 if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
608 (f*be*b*2, 2*b, be*b, b)
612 if e > minExp && f == b^(p-1) then
613 (f*b*2, b^(-e+1)*2, b, 1)
615 (f*2, b^(-e)*2, 1, 1)
621 if b == 2 && base == 10 then
622 -- logBase 10 2 is slightly bigger than 3/10 so
623 -- the following will err on the low side. Ignoring
624 -- the fraction will make it err even more.
625 -- Haskell promises that p-1 <= logBase b f < p.
626 (p - 1 + e0) * 3 `div` 10
628 ceiling ((log (fromInteger (f+1)) +
629 fromIntegral e * log (fromInteger b)) /
630 log (fromInteger base))
631 --WAS: fromInt e * log (fromInteger b))
635 if r + mUp <= expt base n * s then n else fixup (n+1)
637 if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)
641 gen ds rn sN mUpN mDnN =
643 (dn, rn') = (rn * base) `divMod` sN
647 case (rn' < mDnN', rn' + mUpN' > sN) of
648 (True, False) -> dn : ds
649 (False, True) -> dn+1 : ds
650 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
651 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
655 gen [] r (s * expt base k) mUp mDn
657 let bk = expt base (-k) in
658 gen [] (r * bk) s (mUp * bk) (mDn * bk)
660 (map fromIntegral (reverse rds), k)
665 %*********************************************************
667 \subsection{Converting from a Rational to a RealFloat
669 %*********************************************************
671 [In response to a request for documentation of how fromRational works,
672 Joe Fasel writes:] A quite reasonable request! This code was added to
673 the Prelude just before the 1.2 release, when Lennart, working with an
674 early version of hbi, noticed that (read . show) was not the identity
675 for floating-point numbers. (There was a one-bit error about half the
676 time.) The original version of the conversion function was in fact
677 simply a floating-point divide, as you suggest above. The new version
678 is, I grant you, somewhat denser.
680 Unfortunately, Joe's code doesn't work! Here's an example:
682 main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")
687 1.8217369128763981e-300
692 fromRat :: (RealFloat a) => Rational -> a
696 -- If the exponent of the nearest floating-point number to x
697 -- is e, then the significand is the integer nearest xb^(-e),
698 -- where b is the floating-point radix. We start with a good
699 -- guess for e, and if it is correct, the exponent of the
700 -- floating-point number we construct will again be e. If
701 -- not, one more iteration is needed.
703 f e = if e' == e then y else f e'
704 where y = encodeFloat (round (x * (1 % b)^^e)) e
705 (_,e') = decodeFloat y
708 -- We obtain a trial exponent by doing a floating-point
709 -- division of x's numerator by its denominator. The
710 -- result of this division may not itself be the ultimate
711 -- result, because of an accumulation of three rounding
714 (s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
715 / fromInteger (denominator x))
718 Now, here's Lennart's code (which works)
721 -- | Converts a 'Rational' value into any type in class 'RealFloat'.
722 {-# SPECIALISE fromRat :: Rational -> Double,
723 Rational -> Float #-}
724 fromRat :: (RealFloat a) => Rational -> a
726 -- Deal with special cases first, delegating the real work to fromRat'
727 fromRat (n :% 0) | n > 0 = 1/0 -- +Infinity
728 | n < 0 = -1/0 -- -Infinity
729 | otherwise = 0/0 -- NaN
731 fromRat (n :% d) | n > 0 = fromRat' (n :% d)
732 | n < 0 = - fromRat' ((-n) :% d)
733 | otherwise = encodeFloat 0 0 -- Zero
735 -- Conversion process:
736 -- Scale the rational number by the RealFloat base until
737 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
738 -- Then round the rational to an Integer and encode it with the exponent
739 -- that we got from the scaling.
740 -- To speed up the scaling process we compute the log2 of the number to get
741 -- a first guess of the exponent.
743 fromRat' :: (RealFloat a) => Rational -> a
744 -- Invariant: argument is strictly positive
746 where b = floatRadix r
748 (minExp0, _) = floatRange r
749 minExp = minExp0 - p -- the real minimum exponent
750 xMin = toRational (expt b (p-1))
751 xMax = toRational (expt b p)
752 p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp
753 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
754 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
755 r = encodeFloat (round x') p'
757 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
758 scaleRat :: Rational -> Int -> Rational -> Rational -> Int -> Rational -> (Rational, Int)
759 scaleRat b minExp xMin xMax p x
760 | p <= minExp = (x, p)
761 | x >= xMax = scaleRat b minExp xMin xMax (p+1) (x/b)
762 | x < xMin = scaleRat b minExp xMin xMax (p-1) (x*b)
765 -- Exponentiation with a cache for the most common numbers.
766 minExpt, maxExpt :: Int
770 expt :: Integer -> Int -> Integer
772 if base == 2 && n >= minExpt && n <= maxExpt then
777 expts :: Array Int Integer
778 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
780 -- Compute the (floor of the) log of i in base b.
781 -- Simplest way would be just divide i by b until it's smaller then b, but that would
782 -- be very slow! We are just slightly more clever.
783 integerLogBase :: Integer -> Integer -> Int
786 | otherwise = doDiv (i `div` (b^l)) l
788 -- Try squaring the base first to cut down the number of divisions.
789 l = 2 * integerLogBase (b*b) i
791 doDiv :: Integer -> Int -> Int
794 | otherwise = doDiv (x `div` b) (y+1)
799 %*********************************************************
801 \subsection{Floating point numeric primops}
803 %*********************************************************
805 Definitions of the boxed PrimOps; these will be
806 used in the case of partial applications, etc.
809 plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float
810 plusFloat (F# x) (F# y) = F# (plusFloat# x y)
811 minusFloat (F# x) (F# y) = F# (minusFloat# x y)
812 timesFloat (F# x) (F# y) = F# (timesFloat# x y)
813 divideFloat (F# x) (F# y) = F# (divideFloat# x y)
815 negateFloat :: Float -> Float
816 negateFloat (F# x) = F# (negateFloat# x)
818 gtFloat, geFloat, eqFloat, neFloat, ltFloat, leFloat :: Float -> Float -> Bool
819 gtFloat (F# x) (F# y) = gtFloat# x y
820 geFloat (F# x) (F# y) = geFloat# x y
821 eqFloat (F# x) (F# y) = eqFloat# x y
822 neFloat (F# x) (F# y) = neFloat# x y
823 ltFloat (F# x) (F# y) = ltFloat# x y
824 leFloat (F# x) (F# y) = leFloat# x y
826 float2Int :: Float -> Int
827 float2Int (F# x) = I# (float2Int# x)
829 int2Float :: Int -> Float
830 int2Float (I# x) = F# (int2Float# x)
832 expFloat, logFloat, sqrtFloat :: Float -> Float
833 sinFloat, cosFloat, tanFloat :: Float -> Float
834 asinFloat, acosFloat, atanFloat :: Float -> Float
835 sinhFloat, coshFloat, tanhFloat :: Float -> Float
836 expFloat (F# x) = F# (expFloat# x)
837 logFloat (F# x) = F# (logFloat# x)
838 sqrtFloat (F# x) = F# (sqrtFloat# x)
839 sinFloat (F# x) = F# (sinFloat# x)
840 cosFloat (F# x) = F# (cosFloat# x)
841 tanFloat (F# x) = F# (tanFloat# x)
842 asinFloat (F# x) = F# (asinFloat# x)
843 acosFloat (F# x) = F# (acosFloat# x)
844 atanFloat (F# x) = F# (atanFloat# x)
845 sinhFloat (F# x) = F# (sinhFloat# x)
846 coshFloat (F# x) = F# (coshFloat# x)
847 tanhFloat (F# x) = F# (tanhFloat# x)
849 powerFloat :: Float -> Float -> Float
850 powerFloat (F# x) (F# y) = F# (powerFloat# x y)
852 -- definitions of the boxed PrimOps; these will be
853 -- used in the case of partial applications, etc.
855 plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double
856 plusDouble (D# x) (D# y) = D# (x +## y)
857 minusDouble (D# x) (D# y) = D# (x -## y)
858 timesDouble (D# x) (D# y) = D# (x *## y)
859 divideDouble (D# x) (D# y) = D# (x /## y)
861 negateDouble :: Double -> Double
862 negateDouble (D# x) = D# (negateDouble# x)
864 gtDouble, geDouble, eqDouble, neDouble, leDouble, ltDouble :: Double -> Double -> Bool
865 gtDouble (D# x) (D# y) = x >## y
866 geDouble (D# x) (D# y) = x >=## y
867 eqDouble (D# x) (D# y) = x ==## y
868 neDouble (D# x) (D# y) = x /=## y
869 ltDouble (D# x) (D# y) = x <## y
870 leDouble (D# x) (D# y) = x <=## y
872 double2Int :: Double -> Int
873 double2Int (D# x) = I# (double2Int# x)
875 int2Double :: Int -> Double
876 int2Double (I# x) = D# (int2Double# x)
878 double2Float :: Double -> Float
879 double2Float (D# x) = F# (double2Float# x)
881 float2Double :: Float -> Double
882 float2Double (F# x) = D# (float2Double# x)
884 expDouble, logDouble, sqrtDouble :: Double -> Double
885 sinDouble, cosDouble, tanDouble :: Double -> Double
886 asinDouble, acosDouble, atanDouble :: Double -> Double
887 sinhDouble, coshDouble, tanhDouble :: Double -> Double
888 expDouble (D# x) = D# (expDouble# x)
889 logDouble (D# x) = D# (logDouble# x)
890 sqrtDouble (D# x) = D# (sqrtDouble# x)
891 sinDouble (D# x) = D# (sinDouble# x)
892 cosDouble (D# x) = D# (cosDouble# x)
893 tanDouble (D# x) = D# (tanDouble# x)
894 asinDouble (D# x) = D# (asinDouble# x)
895 acosDouble (D# x) = D# (acosDouble# x)
896 atanDouble (D# x) = D# (atanDouble# x)
897 sinhDouble (D# x) = D# (sinhDouble# x)
898 coshDouble (D# x) = D# (coshDouble# x)
899 tanhDouble (D# x) = D# (tanhDouble# x)
901 powerDouble :: Double -> Double -> Double
902 powerDouble (D# x) (D# y) = D# (x **## y)
906 foreign import ccall unsafe "__encodeFloat"
907 encodeFloat# :: Int# -> ByteArray# -> Int -> Float
908 foreign import ccall unsafe "__int_encodeFloat"
909 int_encodeFloat# :: Int# -> Int -> Float
912 foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int
913 foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int
914 foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int
915 foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int
918 foreign import ccall unsafe "__encodeDouble"
919 encodeDouble# :: Int# -> ByteArray# -> Int -> Double
921 foreign import ccall unsafe "isDoubleNaN" isDoubleNaN :: Double -> Int
922 foreign import ccall unsafe "isDoubleInfinite" isDoubleInfinite :: Double -> Int
923 foreign import ccall unsafe "isDoubleDenormalized" isDoubleDenormalized :: Double -> Int
924 foreign import ccall unsafe "isDoubleNegativeZero" isDoubleNegativeZero :: Double -> Int
927 %*********************************************************
929 \subsection{Coercion rules}
931 %*********************************************************
935 "fromIntegral/Int->Float" fromIntegral = int2Float
936 "fromIntegral/Int->Double" fromIntegral = int2Double
937 "realToFrac/Float->Float" realToFrac = id :: Float -> Float
938 "realToFrac/Float->Double" realToFrac = float2Double
939 "realToFrac/Double->Float" realToFrac = double2Float
940 "realToFrac/Double->Double" realToFrac = id :: Double -> Double
941 "realToFrac/Int->Double" realToFrac = int2Double -- See Note [realToFrac int-to-float]
942 "realToFrac/Int->Float" realToFrac = int2Float -- ..ditto
946 Note [realToFrac int-to-float]
947 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
948 Don found that the RULES for realToFrac/Int->Double and simliarly
949 Float made a huge difference to some stream-fusion programs. Here's
952 import Data.Array.Vector
957 let c = replicateU n (2::Double)
958 a = mapU realToFrac (enumFromToU 0 (n-1) ) :: UArr Double
959 print (sumU (zipWithU (*) c a))
961 Without the RULE we get this loop body:
963 case $wtoRational sc_sY4 of ww_aM7 { (# ww1_aM9, ww2_aMa #) ->
964 case $wfromRat ww1_aM9 ww2_aMa of tpl_X1P { D# ipv_sW3 ->
968 (+## sc2_sY6 (*## 2.0 ipv_sW3))
975 (+## sc2_sXV (*## 2.0 (int2Double# sc_sXT)))
977 The running time of the program goes from 120 seconds to 0.198 seconds
978 with the native backend, and 0.143 seconds with the C backend.
980 A few more details in Trac #2251, and the patch message
981 "Add RULES for realToFrac from Int".
983 %*********************************************************
987 %*********************************************************
990 showSignedFloat :: (RealFloat a)
991 => (a -> ShowS) -- ^ a function that can show unsigned values
992 -> Int -- ^ the precedence of the enclosing context
993 -> a -- ^ the value to show
995 showSignedFloat showPos p x
996 | x < 0 || isNegativeZero x
997 = showParen (p > 6) (showChar '-' . showPos (-x))
998 | otherwise = showPos x