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# ) where
36 %*********************************************************
38 \subsection{Standard numeric classes}
40 %*********************************************************
43 -- | Trigonometric and hyperbolic functions and related functions.
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
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
57 x ** y = exp (log x * y)
58 logBase x y = log y / log x
61 tanh x = sinh x / cosh x
63 -- | Efficient, machine-independent access to the components of a
64 -- floating-point number.
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
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'.
90 -- | the first component of 'decodeFloat', scaled to lie in the open
91 -- interval (@-1@,@1@)
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
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
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
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.
118 exponent x = if m == 0 then 0 else n + floatDigits x
119 where (m,n) = decodeFloat x
121 significand x = encodeFloat m (negate (floatDigits x))
122 where (m,_) = decodeFloat x
124 scaleFloat k x = encodeFloat m (n+k)
125 where (m,n) = decodeFloat 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)
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 +)
142 %*********************************************************
144 \subsection{Type @Integer@, @Float@, @Double@}
146 %*********************************************************
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#
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#
161 %*********************************************************
163 \subsection{Type @Float@}
165 %*********************************************************
168 instance Eq Float where
169 (F# x) == (F# y) = x `eqFloat#` y
171 instance Ord Float where
172 (F# x) `compare` (F# y) | x `ltFloat#` y = LT
173 | x `eqFloat#` y = EQ
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
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
187 | otherwise = negateFloat x
188 signum x | x == 0.0 = 0
190 | otherwise = negate 1
192 {-# INLINE fromInteger #-}
193 fromInteger i = F# (floatFromInteger i)
195 instance Real Float where
196 toRational x = (m%1)*(b%1)^^n
197 where (m,n) = decodeFloat x
200 instance Fractional Float where
201 (/) x y = divideFloat x y
202 fromRational x = fromRat x
205 {-# RULES "truncate/Float->Int" truncate = float2Int #-}
206 instance RealFrac Float where
208 {-# SPECIALIZE properFraction :: Float -> (Int, Float) #-}
209 {-# SPECIALIZE round :: Float -> Int #-}
211 {-# SPECIALIZE properFraction :: Float -> (Integer, Float) #-}
212 {-# SPECIALIZE round :: Float -> Integer #-}
214 -- ceiling, floor, and truncate are all small
215 {-# INLINE ceiling #-}
217 {-# INLINE truncate #-}
220 = case (decodeFloat x) of { (m,n) ->
221 let b = floatRadix x in
223 (fromInteger m * fromInteger b ^ n, 0.0)
225 case (quotRem m (b^(negate n))) of { (w,r) ->
226 (fromInteger w, encodeFloat r n)
230 truncate x = case properFraction x of
233 round x = case properFraction x of
235 m = if r < 0.0 then n - 1 else n + 1
236 half_down = abs r - 0.5
238 case (compare half_down 0.0) of
240 EQ -> if even n then n else m
243 ceiling x = case properFraction x of
244 (n,r) -> if r > 0.0 then n + 1 else n
246 floor x = case properFraction x of
247 (n,r) -> if r < 0.0 then n - 1 else n
249 instance Floating Float where
250 pi = 3.141592653589793238
263 (**) x y = powerFloat x y
264 logBase x y = log y / log x
266 asinh x = log (x + sqrt (1.0+x*x))
267 acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
268 atanh x = log ((x+1.0) / sqrt (1.0-x*x))
270 instance RealFloat Float where
271 floatRadix _ = FLT_RADIX -- from float.h
272 floatDigits _ = FLT_MANT_DIG -- ditto
273 floatRange _ = (FLT_MIN_EXP, FLT_MAX_EXP) -- ditto
275 decodeFloat (F# f#) = case decodeFloatInteger f# of
276 (# i, e #) -> (i, I# e)
278 encodeFloat i (I# e) = F# (encodeFloatInteger i e)
280 exponent x = case decodeFloat x of
281 (m,n) -> if m == 0 then 0 else n + floatDigits x
283 significand x = case decodeFloat x of
284 (m,_) -> encodeFloat m (negate (floatDigits x))
286 scaleFloat k x = case decodeFloat x of
287 (m,n) -> encodeFloat m (n+k)
288 isNaN x = 0 /= isFloatNaN x
289 isInfinite x = 0 /= isFloatInfinite x
290 isDenormalized x = 0 /= isFloatDenormalized x
291 isNegativeZero x = 0 /= isFloatNegativeZero x
294 instance Show Float where
295 showsPrec x = showSignedFloat showFloat x
296 showList = showList__ (showsPrec 0)
299 %*********************************************************
301 \subsection{Type @Double@}
303 %*********************************************************
306 instance Eq Double where
307 (D# x) == (D# y) = x ==## y
309 instance Ord Double where
310 (D# x) `compare` (D# y) | x <## y = LT
314 (D# x) < (D# y) = x <## y
315 (D# x) <= (D# y) = x <=## y
316 (D# x) >= (D# y) = x >=## y
317 (D# x) > (D# y) = x >## y
319 instance Num Double where
320 (+) x y = plusDouble x y
321 (-) x y = minusDouble x y
322 negate x = negateDouble x
323 (*) x y = timesDouble x y
325 | otherwise = negateDouble x
326 signum x | x == 0.0 = 0
328 | otherwise = negate 1
330 {-# INLINE fromInteger #-}
331 fromInteger i = D# (doubleFromInteger i)
334 instance Real Double where
335 toRational x = (m%1)*(b%1)^^n
336 where (m,n) = decodeFloat x
339 instance Fractional Double where
340 (/) x y = divideDouble x y
341 fromRational x = fromRat x
344 instance Floating Double where
345 pi = 3.141592653589793238
348 sqrt x = sqrtDouble x
352 asin x = asinDouble x
353 acos x = acosDouble x
354 atan x = atanDouble x
355 sinh x = sinhDouble x
356 cosh x = coshDouble x
357 tanh x = tanhDouble x
358 (**) x y = powerDouble x y
359 logBase x y = log y / log x
361 asinh x = log (x + sqrt (1.0+x*x))
362 acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
363 atanh x = log ((x+1.0) / sqrt (1.0-x*x))
365 {-# RULES "truncate/Double->Int" truncate = double2Int #-}
366 instance RealFrac Double where
368 {-# SPECIALIZE properFraction :: Double -> (Int, Double) #-}
369 {-# SPECIALIZE round :: Double -> Int #-}
371 {-# SPECIALIZE properFraction :: Double -> (Integer, Double) #-}
372 {-# SPECIALIZE round :: Double -> Integer #-}
374 -- ceiling, floor, and truncate are all small
375 {-# INLINE ceiling #-}
377 {-# INLINE truncate #-}
380 = case (decodeFloat x) of { (m,n) ->
381 let b = floatRadix x in
383 (fromInteger m * fromInteger b ^ n, 0.0)
385 case (quotRem m (b^(negate n))) of { (w,r) ->
386 (fromInteger w, encodeFloat r n)
390 truncate x = case properFraction x of
393 round x = case properFraction x of
395 m = if r < 0.0 then n - 1 else n + 1
396 half_down = abs r - 0.5
398 case (compare half_down 0.0) of
400 EQ -> if even n then n else m
403 ceiling x = case properFraction x of
404 (n,r) -> if r > 0.0 then n + 1 else n
406 floor x = case properFraction x of
407 (n,r) -> if r < 0.0 then n - 1 else n
409 instance RealFloat Double where
410 floatRadix _ = FLT_RADIX -- from float.h
411 floatDigits _ = DBL_MANT_DIG -- ditto
412 floatRange _ = (DBL_MIN_EXP, DBL_MAX_EXP) -- ditto
415 = case decodeDoubleInteger x# of
416 (# i, j #) -> (i, I# j)
418 encodeFloat i (I# j) = D# (encodeDoubleInteger i j)
420 exponent x = case decodeFloat x of
421 (m,n) -> if m == 0 then 0 else n + floatDigits x
423 significand x = case decodeFloat x of
424 (m,_) -> encodeFloat m (negate (floatDigits x))
426 scaleFloat k x = case decodeFloat x of
427 (m,n) -> encodeFloat m (n+k)
429 isNaN x = 0 /= isDoubleNaN x
430 isInfinite x = 0 /= isDoubleInfinite x
431 isDenormalized x = 0 /= isDoubleDenormalized x
432 isNegativeZero x = 0 /= isDoubleNegativeZero x
435 instance Show Double where
436 showsPrec x = showSignedFloat showFloat x
437 showList = showList__ (showsPrec 0)
440 %*********************************************************
442 \subsection{@Enum@ instances}
444 %*********************************************************
446 The @Enum@ instances for Floats and Doubles are slightly unusual.
447 The @toEnum@ function truncates numbers to Int. The definitions
448 of @enumFrom@ and @enumFromThen@ allow floats to be used in arithmetic
449 series: [0,0.1 .. 1.0]. However, roundoff errors make these somewhat
450 dubious. This example may have either 10 or 11 elements, depending on
451 how 0.1 is represented.
453 NOTE: The instances for Float and Double do not make use of the default
454 methods for @enumFromTo@ and @enumFromThenTo@, as these rely on there being
455 a `non-lossy' conversion to and from Ints. Instead we make use of the
456 1.2 default methods (back in the days when Enum had Ord as a superclass)
457 for these (@numericEnumFromTo@ and @numericEnumFromThenTo@ below.)
460 instance Enum Float where
464 fromEnum = fromInteger . truncate -- may overflow
465 enumFrom = numericEnumFrom
466 enumFromTo = numericEnumFromTo
467 enumFromThen = numericEnumFromThen
468 enumFromThenTo = numericEnumFromThenTo
470 instance Enum Double where
474 fromEnum = fromInteger . truncate -- may overflow
475 enumFrom = numericEnumFrom
476 enumFromTo = numericEnumFromTo
477 enumFromThen = numericEnumFromThen
478 enumFromThenTo = numericEnumFromThenTo
482 %*********************************************************
484 \subsection{Printing floating point}
486 %*********************************************************
490 -- | Show a signed 'RealFloat' value to full precision
491 -- using standard decimal notation for arguments whose absolute value lies
492 -- between @0.1@ and @9,999,999@, and scientific notation otherwise.
493 showFloat :: (RealFloat a) => a -> ShowS
494 showFloat x = showString (formatRealFloat FFGeneric Nothing x)
496 -- These are the format types. This type is not exported.
498 data FFFormat = FFExponent | FFFixed | FFGeneric
500 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
501 formatRealFloat fmt decs x
503 | isInfinite x = if x < 0 then "-Infinity" else "Infinity"
504 | x < 0 || isNegativeZero x = '-':doFmt fmt (floatToDigits (toInteger base) (-x))
505 | otherwise = doFmt fmt (floatToDigits (toInteger base) x)
509 doFmt format (is, e) =
510 let ds = map intToDigit is in
513 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
518 let show_e' = show (e-1) in
521 [d] -> d : ".0e" ++ show_e'
522 (d:ds') -> d : '.' : ds' ++ "e" ++ show_e'
523 [] -> error "formatRealFloat/doFmt/FFExponent: []"
525 let dec' = max dec 1 in
527 [0] -> '0' :'.' : take dec' (repeat '0') ++ "e0"
530 (ei,is') = roundTo base (dec'+1) is
531 (d:ds') = map intToDigit (if ei > 0 then init is' else is')
533 d:'.':ds' ++ 'e':show (e-1+ei)
536 mk0 ls = case ls of { "" -> "0" ; _ -> ls}
540 | e <= 0 -> "0." ++ replicate (-e) '0' ++ ds
543 f 0 s rs = mk0 (reverse s) ++ '.':mk0 rs
544 f n s "" = f (n-1) ('0':s) ""
545 f n s (r:rs) = f (n-1) (r:s) rs
549 let dec' = max dec 0 in
552 (ei,is') = roundTo base (dec' + e) is
553 (ls,rs) = splitAt (e+ei) (map intToDigit is')
555 mk0 ls ++ (if null rs then "" else '.':rs)
558 (ei,is') = roundTo base dec' (replicate (-e) 0 ++ is)
559 d:ds' = map intToDigit (if ei > 0 then is' else 0:is')
561 d : (if null ds' then "" else '.':ds')
564 roundTo :: Int -> Int -> [Int] -> (Int,[Int])
569 _ -> error "roundTo: bad Value"
573 f n [] = (0, replicate n 0)
574 f 0 (x:_) = (if x >= b2 then 1 else 0, [])
576 | i' == base = (1,0:ds)
577 | otherwise = (0,i':ds)
582 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
583 -- by R.G. Burger and R.K. Dybvig in PLDI 96.
584 -- This version uses a much slower logarithm estimator. It should be improved.
586 -- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,
587 -- and returns a list of digits and an exponent.
588 -- In particular, if @x>=0@, and
590 -- > floatToDigits base x = ([d1,d2,...,dn], e)
596 -- (2) @x = 0.d1d2...dn * (base**e)@
598 -- (3) @0 <= di <= base-1@
600 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
601 floatToDigits _ 0 = ([0], 0)
602 floatToDigits base x =
604 (f0, e0) = decodeFloat x
605 (minExp0, _) = floatRange x
608 minExp = minExp0 - p -- the real minimum exponent
609 -- Haskell requires that f be adjusted so denormalized numbers
610 -- will have an impossibly low exponent. Adjust for this.
612 let n = minExp - e0 in
613 if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
618 (f*be*b*2, 2*b, be*b, b)
622 if e > minExp && f == b^(p-1) then
623 (f*b*2, b^(-e+1)*2, b, 1)
625 (f*2, b^(-e)*2, 1, 1)
631 if b == 2 && base == 10 then
632 -- logBase 10 2 is slightly bigger than 3/10 so
633 -- the following will err on the low side. Ignoring
634 -- the fraction will make it err even more.
635 -- Haskell promises that p-1 <= logBase b f < p.
636 (p - 1 + e0) * 3 `div` 10
638 ceiling ((log (fromInteger (f+1)) +
639 fromIntegral e * log (fromInteger b)) /
640 log (fromInteger base))
641 --WAS: fromInt e * log (fromInteger b))
645 if r + mUp <= expt base n * s then n else fixup (n+1)
647 if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)
651 gen ds rn sN mUpN mDnN =
653 (dn, rn') = (rn * base) `divMod` sN
657 case (rn' < mDnN', rn' + mUpN' > sN) of
658 (True, False) -> dn : ds
659 (False, True) -> dn+1 : ds
660 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
661 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
665 gen [] r (s * expt base k) mUp mDn
667 let bk = expt base (-k) in
668 gen [] (r * bk) s (mUp * bk) (mDn * bk)
670 (map fromIntegral (reverse rds), k)
675 %*********************************************************
677 \subsection{Converting from a Rational to a RealFloat
679 %*********************************************************
681 [In response to a request for documentation of how fromRational works,
682 Joe Fasel writes:] A quite reasonable request! This code was added to
683 the Prelude just before the 1.2 release, when Lennart, working with an
684 early version of hbi, noticed that (read . show) was not the identity
685 for floating-point numbers. (There was a one-bit error about half the
686 time.) The original version of the conversion function was in fact
687 simply a floating-point divide, as you suggest above. The new version
688 is, I grant you, somewhat denser.
690 Unfortunately, Joe's code doesn't work! Here's an example:
692 main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")
697 1.8217369128763981e-300
702 fromRat :: (RealFloat a) => Rational -> a
706 -- If the exponent of the nearest floating-point number to x
707 -- is e, then the significand is the integer nearest xb^(-e),
708 -- where b is the floating-point radix. We start with a good
709 -- guess for e, and if it is correct, the exponent of the
710 -- floating-point number we construct will again be e. If
711 -- not, one more iteration is needed.
713 f e = if e' == e then y else f e'
714 where y = encodeFloat (round (x * (1 % b)^^e)) e
715 (_,e') = decodeFloat y
718 -- We obtain a trial exponent by doing a floating-point
719 -- division of x's numerator by its denominator. The
720 -- result of this division may not itself be the ultimate
721 -- result, because of an accumulation of three rounding
724 (s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
725 / fromInteger (denominator x))
728 Now, here's Lennart's code (which works)
731 -- | Converts a 'Rational' value into any type in class 'RealFloat'.
732 {-# SPECIALISE fromRat :: Rational -> Double,
733 Rational -> Float #-}
734 fromRat :: (RealFloat a) => Rational -> a
736 -- Deal with special cases first, delegating the real work to fromRat'
737 fromRat (n :% 0) | n > 0 = 1/0 -- +Infinity
738 | n < 0 = -1/0 -- -Infinity
739 | otherwise = 0/0 -- NaN
741 fromRat (n :% d) | n > 0 = fromRat' (n :% d)
742 | n < 0 = - fromRat' ((-n) :% d)
743 | otherwise = encodeFloat 0 0 -- Zero
745 -- Conversion process:
746 -- Scale the rational number by the RealFloat base until
747 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
748 -- Then round the rational to an Integer and encode it with the exponent
749 -- that we got from the scaling.
750 -- To speed up the scaling process we compute the log2 of the number to get
751 -- a first guess of the exponent.
753 fromRat' :: (RealFloat a) => Rational -> a
754 -- Invariant: argument is strictly positive
756 where b = floatRadix r
758 (minExp0, _) = floatRange r
759 minExp = minExp0 - p -- the real minimum exponent
760 xMin = toRational (expt b (p-1))
761 xMax = toRational (expt b p)
762 p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp
763 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
764 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
765 r = encodeFloat (round x') p'
767 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
768 scaleRat :: Rational -> Int -> Rational -> Rational -> Int -> Rational -> (Rational, Int)
769 scaleRat b minExp xMin xMax p x
770 | p <= minExp = (x, p)
771 | x >= xMax = scaleRat b minExp xMin xMax (p+1) (x/b)
772 | x < xMin = scaleRat b minExp xMin xMax (p-1) (x*b)
775 -- Exponentiation with a cache for the most common numbers.
776 minExpt, maxExpt :: Int
780 expt :: Integer -> Int -> Integer
782 if base == 2 && n >= minExpt && n <= maxExpt then
787 expts :: Array Int Integer
788 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
790 -- Compute the (floor of the) log of i in base b.
791 -- Simplest way would be just divide i by b until it's smaller then b, but that would
792 -- be very slow! We are just slightly more clever.
793 integerLogBase :: Integer -> Integer -> Int
796 | otherwise = doDiv (i `div` (b^l)) l
798 -- Try squaring the base first to cut down the number of divisions.
799 l = 2 * integerLogBase (b*b) i
801 doDiv :: Integer -> Int -> Int
804 | otherwise = doDiv (x `div` b) (y+1)
809 %*********************************************************
811 \subsection{Floating point numeric primops}
813 %*********************************************************
815 Definitions of the boxed PrimOps; these will be
816 used in the case of partial applications, etc.
819 plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float
820 plusFloat (F# x) (F# y) = F# (plusFloat# x y)
821 minusFloat (F# x) (F# y) = F# (minusFloat# x y)
822 timesFloat (F# x) (F# y) = F# (timesFloat# x y)
823 divideFloat (F# x) (F# y) = F# (divideFloat# x y)
825 negateFloat :: Float -> Float
826 negateFloat (F# x) = F# (negateFloat# x)
828 gtFloat, geFloat, eqFloat, neFloat, ltFloat, leFloat :: Float -> Float -> Bool
829 gtFloat (F# x) (F# y) = gtFloat# x y
830 geFloat (F# x) (F# y) = geFloat# x y
831 eqFloat (F# x) (F# y) = eqFloat# x y
832 neFloat (F# x) (F# y) = neFloat# x y
833 ltFloat (F# x) (F# y) = ltFloat# x y
834 leFloat (F# x) (F# y) = leFloat# x y
836 float2Int :: Float -> Int
837 float2Int (F# x) = I# (float2Int# x)
839 int2Float :: Int -> Float
840 int2Float (I# x) = F# (int2Float# x)
842 expFloat, logFloat, sqrtFloat :: Float -> Float
843 sinFloat, cosFloat, tanFloat :: Float -> Float
844 asinFloat, acosFloat, atanFloat :: Float -> Float
845 sinhFloat, coshFloat, tanhFloat :: Float -> Float
846 expFloat (F# x) = F# (expFloat# x)
847 logFloat (F# x) = F# (logFloat# x)
848 sqrtFloat (F# x) = F# (sqrtFloat# x)
849 sinFloat (F# x) = F# (sinFloat# x)
850 cosFloat (F# x) = F# (cosFloat# x)
851 tanFloat (F# x) = F# (tanFloat# x)
852 asinFloat (F# x) = F# (asinFloat# x)
853 acosFloat (F# x) = F# (acosFloat# x)
854 atanFloat (F# x) = F# (atanFloat# x)
855 sinhFloat (F# x) = F# (sinhFloat# x)
856 coshFloat (F# x) = F# (coshFloat# x)
857 tanhFloat (F# x) = F# (tanhFloat# x)
859 powerFloat :: Float -> Float -> Float
860 powerFloat (F# x) (F# y) = F# (powerFloat# x y)
862 -- definitions of the boxed PrimOps; these will be
863 -- used in the case of partial applications, etc.
865 plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double
866 plusDouble (D# x) (D# y) = D# (x +## y)
867 minusDouble (D# x) (D# y) = D# (x -## y)
868 timesDouble (D# x) (D# y) = D# (x *## y)
869 divideDouble (D# x) (D# y) = D# (x /## y)
871 negateDouble :: Double -> Double
872 negateDouble (D# x) = D# (negateDouble# x)
874 gtDouble, geDouble, eqDouble, neDouble, leDouble, ltDouble :: Double -> Double -> Bool
875 gtDouble (D# x) (D# y) = x >## y
876 geDouble (D# x) (D# y) = x >=## y
877 eqDouble (D# x) (D# y) = x ==## y
878 neDouble (D# x) (D# y) = x /=## y
879 ltDouble (D# x) (D# y) = x <## y
880 leDouble (D# x) (D# y) = x <=## y
882 double2Int :: Double -> Int
883 double2Int (D# x) = I# (double2Int# x)
885 int2Double :: Int -> Double
886 int2Double (I# x) = D# (int2Double# x)
888 double2Float :: Double -> Float
889 double2Float (D# x) = F# (double2Float# x)
891 float2Double :: Float -> Double
892 float2Double (F# x) = D# (float2Double# x)
894 expDouble, logDouble, sqrtDouble :: Double -> Double
895 sinDouble, cosDouble, tanDouble :: Double -> Double
896 asinDouble, acosDouble, atanDouble :: Double -> Double
897 sinhDouble, coshDouble, tanhDouble :: Double -> Double
898 expDouble (D# x) = D# (expDouble# x)
899 logDouble (D# x) = D# (logDouble# x)
900 sqrtDouble (D# x) = D# (sqrtDouble# x)
901 sinDouble (D# x) = D# (sinDouble# x)
902 cosDouble (D# x) = D# (cosDouble# x)
903 tanDouble (D# x) = D# (tanDouble# x)
904 asinDouble (D# x) = D# (asinDouble# x)
905 acosDouble (D# x) = D# (acosDouble# x)
906 atanDouble (D# x) = D# (atanDouble# x)
907 sinhDouble (D# x) = D# (sinhDouble# x)
908 coshDouble (D# x) = D# (coshDouble# x)
909 tanhDouble (D# x) = D# (tanhDouble# x)
911 powerDouble :: Double -> Double -> Double
912 powerDouble (D# x) (D# y) = D# (x **## y)
916 foreign import ccall unsafe "__encodeFloat"
917 encodeFloat# :: Int# -> ByteArray# -> Int -> Float
918 foreign import ccall unsafe "__int_encodeFloat"
919 int_encodeFloat# :: Int# -> Int -> Float
922 foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int
923 foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int
924 foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int
925 foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int
928 foreign import ccall unsafe "__encodeDouble"
929 encodeDouble# :: Int# -> ByteArray# -> Int -> Double
931 foreign import ccall unsafe "isDoubleNaN" isDoubleNaN :: Double -> Int
932 foreign import ccall unsafe "isDoubleInfinite" isDoubleInfinite :: Double -> Int
933 foreign import ccall unsafe "isDoubleDenormalized" isDoubleDenormalized :: Double -> Int
934 foreign import ccall unsafe "isDoubleNegativeZero" isDoubleNegativeZero :: Double -> Int
937 %*********************************************************
939 \subsection{Coercion rules}
941 %*********************************************************
945 "fromIntegral/Int->Float" fromIntegral = int2Float
946 "fromIntegral/Int->Double" fromIntegral = int2Double
947 "realToFrac/Float->Float" realToFrac = id :: Float -> Float
948 "realToFrac/Float->Double" realToFrac = float2Double
949 "realToFrac/Double->Float" realToFrac = double2Float
950 "realToFrac/Double->Double" realToFrac = id :: Double -> Double
951 "realToFrac/Int->Double" realToFrac = int2Double -- See Note [realToFrac int-to-float]
952 "realToFrac/Int->Float" realToFrac = int2Float -- ..ditto
956 Note [realToFrac int-to-float]
957 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
958 Don found that the RULES for realToFrac/Int->Double and simliarly
959 Float made a huge difference to some stream-fusion programs. Here's
962 import Data.Array.Vector
967 let c = replicateU n (2::Double)
968 a = mapU realToFrac (enumFromToU 0 (n-1) ) :: UArr Double
969 print (sumU (zipWithU (*) c a))
971 Without the RULE we get this loop body:
973 case $wtoRational sc_sY4 of ww_aM7 { (# ww1_aM9, ww2_aMa #) ->
974 case $wfromRat ww1_aM9 ww2_aMa of tpl_X1P { D# ipv_sW3 ->
978 (+## sc2_sY6 (*## 2.0 ipv_sW3))
985 (+## sc2_sXV (*## 2.0 (int2Double# sc_sXT)))
987 The running time of the program goes from 120 seconds to 0.198 seconds
988 with the native backend, and 0.143 seconds with the C backend.
990 A few more details in Trac #2251, and the patch message
991 "Add RULES for realToFrac from Int".
993 %*********************************************************
997 %*********************************************************
1000 showSignedFloat :: (RealFloat a)
1001 => (a -> ShowS) -- ^ a function that can show unsigned values
1002 -> Int -- ^ the precedence of the enclosing context
1003 -> a -- ^ the value to show
1005 showSignedFloat showPos p x
1006 | x < 0 || isNegativeZero x
1007 = showParen (p > 6) (showChar '-' . showPos (-x))
1008 | otherwise = showPos x