2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
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'
524 let dec' = max dec 1 in
526 [0] -> '0' :'.' : take dec' (repeat '0') ++ "e0"
529 (ei,is') = roundTo base (dec'+1) is
530 (d:ds') = map intToDigit (if ei > 0 then init is' else is')
532 d:'.':ds' ++ 'e':show (e-1+ei)
535 mk0 ls = case ls of { "" -> "0" ; _ -> ls}
539 | e <= 0 -> "0." ++ replicate (-e) '0' ++ ds
542 f 0 s rs = mk0 (reverse s) ++ '.':mk0 rs
543 f n s "" = f (n-1) ('0':s) ""
544 f n s (r:rs) = f (n-1) (r:s) rs
548 let dec' = max dec 0 in
551 (ei,is') = roundTo base (dec' + e) is
552 (ls,rs) = splitAt (e+ei) (map intToDigit is')
554 mk0 ls ++ (if null rs then "" else '.':rs)
557 (ei,is') = roundTo base dec' (replicate (-e) 0 ++ is)
558 d:ds' = map intToDigit (if ei > 0 then is' else 0:is')
560 d : (if null ds' then "" else '.':ds')
563 roundTo :: Int -> Int -> [Int] -> (Int,[Int])
571 f n [] = (0, replicate n 0)
572 f 0 (x:_) = (if x >= b2 then 1 else 0, [])
574 | i' == base = (1,0:ds)
575 | otherwise = (0,i':ds)
580 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
581 -- by R.G. Burger and R.K. Dybvig in PLDI 96.
582 -- This version uses a much slower logarithm estimator. It should be improved.
584 -- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,
585 -- and returns a list of digits and an exponent.
586 -- In particular, if @x>=0@, and
588 -- > floatToDigits base x = ([d1,d2,...,dn], e)
594 -- (2) @x = 0.d1d2...dn * (base**e)@
596 -- (3) @0 <= di <= base-1@
598 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
599 floatToDigits _ 0 = ([0], 0)
600 floatToDigits base x =
602 (f0, e0) = decodeFloat x
603 (minExp0, _) = floatRange x
606 minExp = minExp0 - p -- the real minimum exponent
607 -- Haskell requires that f be adjusted so denormalized numbers
608 -- will have an impossibly low exponent. Adjust for this.
610 let n = minExp - e0 in
611 if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
616 (f*be*b*2, 2*b, be*b, b)
620 if e > minExp && f == b^(p-1) then
621 (f*b*2, b^(-e+1)*2, b, 1)
623 (f*2, b^(-e)*2, 1, 1)
629 if b == 2 && base == 10 then
630 -- logBase 10 2 is slightly bigger than 3/10 so
631 -- the following will err on the low side. Ignoring
632 -- the fraction will make it err even more.
633 -- Haskell promises that p-1 <= logBase b f < p.
634 (p - 1 + e0) * 3 `div` 10
636 ceiling ((log (fromInteger (f+1)) +
637 fromIntegral e * log (fromInteger b)) /
638 log (fromInteger base))
639 --WAS: fromInt e * log (fromInteger b))
643 if r + mUp <= expt base n * s then n else fixup (n+1)
645 if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)
649 gen ds rn sN mUpN mDnN =
651 (dn, rn') = (rn * base) `divMod` sN
655 case (rn' < mDnN', rn' + mUpN' > sN) of
656 (True, False) -> dn : ds
657 (False, True) -> dn+1 : ds
658 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
659 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
663 gen [] r (s * expt base k) mUp mDn
665 let bk = expt base (-k) in
666 gen [] (r * bk) s (mUp * bk) (mDn * bk)
668 (map fromIntegral (reverse rds), k)
673 %*********************************************************
675 \subsection{Converting from a Rational to a RealFloat
677 %*********************************************************
679 [In response to a request for documentation of how fromRational works,
680 Joe Fasel writes:] A quite reasonable request! This code was added to
681 the Prelude just before the 1.2 release, when Lennart, working with an
682 early version of hbi, noticed that (read . show) was not the identity
683 for floating-point numbers. (There was a one-bit error about half the
684 time.) The original version of the conversion function was in fact
685 simply a floating-point divide, as you suggest above. The new version
686 is, I grant you, somewhat denser.
688 Unfortunately, Joe's code doesn't work! Here's an example:
690 main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")
695 1.8217369128763981e-300
700 fromRat :: (RealFloat a) => Rational -> a
704 -- If the exponent of the nearest floating-point number to x
705 -- is e, then the significand is the integer nearest xb^(-e),
706 -- where b is the floating-point radix. We start with a good
707 -- guess for e, and if it is correct, the exponent of the
708 -- floating-point number we construct will again be e. If
709 -- not, one more iteration is needed.
711 f e = if e' == e then y else f e'
712 where y = encodeFloat (round (x * (1 % b)^^e)) e
713 (_,e') = decodeFloat y
716 -- We obtain a trial exponent by doing a floating-point
717 -- division of x's numerator by its denominator. The
718 -- result of this division may not itself be the ultimate
719 -- result, because of an accumulation of three rounding
722 (s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
723 / fromInteger (denominator x))
726 Now, here's Lennart's code (which works)
729 -- | Converts a 'Rational' value into any type in class 'RealFloat'.
730 {-# SPECIALISE fromRat :: Rational -> Double,
731 Rational -> Float #-}
732 fromRat :: (RealFloat a) => Rational -> a
734 -- Deal with special cases first, delegating the real work to fromRat'
735 fromRat (n :% 0) | n > 0 = 1/0 -- +Infinity
736 | n == 0 = 0/0 -- NaN
737 | n < 0 = -1/0 -- -Infinity
739 fromRat (n :% d) | n > 0 = fromRat' (n :% d)
740 | n == 0 = encodeFloat 0 0 -- Zero
741 | n < 0 = - fromRat' ((-n) :% d)
743 -- Conversion process:
744 -- Scale the rational number by the RealFloat base until
745 -- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
746 -- Then round the rational to an Integer and encode it with the exponent
747 -- that we got from the scaling.
748 -- To speed up the scaling process we compute the log2 of the number to get
749 -- a first guess of the exponent.
751 fromRat' :: (RealFloat a) => Rational -> a
752 -- Invariant: argument is strictly positive
754 where b = floatRadix r
756 (minExp0, _) = floatRange r
757 minExp = minExp0 - p -- the real minimum exponent
758 xMin = toRational (expt b (p-1))
759 xMax = toRational (expt b p)
760 p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp
761 f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
762 (x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
763 r = encodeFloat (round x') p'
765 -- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
766 scaleRat :: Rational -> Int -> Rational -> Rational -> Int -> Rational -> (Rational, Int)
767 scaleRat b minExp xMin xMax p x
768 | p <= minExp = (x, p)
769 | x >= xMax = scaleRat b minExp xMin xMax (p+1) (x/b)
770 | x < xMin = scaleRat b minExp xMin xMax (p-1) (x*b)
773 -- Exponentiation with a cache for the most common numbers.
774 minExpt, maxExpt :: Int
778 expt :: Integer -> Int -> Integer
780 if base == 2 && n >= minExpt && n <= maxExpt then
785 expts :: Array Int Integer
786 expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
788 -- Compute the (floor of the) log of i in base b.
789 -- Simplest way would be just divide i by b until it's smaller then b, but that would
790 -- be very slow! We are just slightly more clever.
791 integerLogBase :: Integer -> Integer -> Int
794 | otherwise = doDiv (i `div` (b^l)) l
796 -- Try squaring the base first to cut down the number of divisions.
797 l = 2 * integerLogBase (b*b) i
799 doDiv :: Integer -> Int -> Int
802 | otherwise = doDiv (x `div` b) (y+1)
807 %*********************************************************
809 \subsection{Floating point numeric primops}
811 %*********************************************************
813 Definitions of the boxed PrimOps; these will be
814 used in the case of partial applications, etc.
817 plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float
818 plusFloat (F# x) (F# y) = F# (plusFloat# x y)
819 minusFloat (F# x) (F# y) = F# (minusFloat# x y)
820 timesFloat (F# x) (F# y) = F# (timesFloat# x y)
821 divideFloat (F# x) (F# y) = F# (divideFloat# x y)
823 negateFloat :: Float -> Float
824 negateFloat (F# x) = F# (negateFloat# x)
826 gtFloat, geFloat, eqFloat, neFloat, ltFloat, leFloat :: Float -> Float -> Bool
827 gtFloat (F# x) (F# y) = gtFloat# x y
828 geFloat (F# x) (F# y) = geFloat# x y
829 eqFloat (F# x) (F# y) = eqFloat# x y
830 neFloat (F# x) (F# y) = neFloat# x y
831 ltFloat (F# x) (F# y) = ltFloat# x y
832 leFloat (F# x) (F# y) = leFloat# x y
834 float2Int :: Float -> Int
835 float2Int (F# x) = I# (float2Int# x)
837 int2Float :: Int -> Float
838 int2Float (I# x) = F# (int2Float# x)
840 expFloat, logFloat, sqrtFloat :: Float -> Float
841 sinFloat, cosFloat, tanFloat :: Float -> Float
842 asinFloat, acosFloat, atanFloat :: Float -> Float
843 sinhFloat, coshFloat, tanhFloat :: Float -> Float
844 expFloat (F# x) = F# (expFloat# x)
845 logFloat (F# x) = F# (logFloat# x)
846 sqrtFloat (F# x) = F# (sqrtFloat# x)
847 sinFloat (F# x) = F# (sinFloat# x)
848 cosFloat (F# x) = F# (cosFloat# x)
849 tanFloat (F# x) = F# (tanFloat# x)
850 asinFloat (F# x) = F# (asinFloat# x)
851 acosFloat (F# x) = F# (acosFloat# x)
852 atanFloat (F# x) = F# (atanFloat# x)
853 sinhFloat (F# x) = F# (sinhFloat# x)
854 coshFloat (F# x) = F# (coshFloat# x)
855 tanhFloat (F# x) = F# (tanhFloat# x)
857 powerFloat :: Float -> Float -> Float
858 powerFloat (F# x) (F# y) = F# (powerFloat# x y)
860 -- definitions of the boxed PrimOps; these will be
861 -- used in the case of partial applications, etc.
863 plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double
864 plusDouble (D# x) (D# y) = D# (x +## y)
865 minusDouble (D# x) (D# y) = D# (x -## y)
866 timesDouble (D# x) (D# y) = D# (x *## y)
867 divideDouble (D# x) (D# y) = D# (x /## y)
869 negateDouble :: Double -> Double
870 negateDouble (D# x) = D# (negateDouble# x)
872 gtDouble, geDouble, eqDouble, neDouble, leDouble, ltDouble :: Double -> Double -> Bool
873 gtDouble (D# x) (D# y) = x >## y
874 geDouble (D# x) (D# y) = x >=## y
875 eqDouble (D# x) (D# y) = x ==## y
876 neDouble (D# x) (D# y) = x /=## y
877 ltDouble (D# x) (D# y) = x <## y
878 leDouble (D# x) (D# y) = x <=## y
880 double2Int :: Double -> Int
881 double2Int (D# x) = I# (double2Int# x)
883 int2Double :: Int -> Double
884 int2Double (I# x) = D# (int2Double# x)
886 double2Float :: Double -> Float
887 double2Float (D# x) = F# (double2Float# x)
889 float2Double :: Float -> Double
890 float2Double (F# x) = D# (float2Double# x)
892 expDouble, logDouble, sqrtDouble :: Double -> Double
893 sinDouble, cosDouble, tanDouble :: Double -> Double
894 asinDouble, acosDouble, atanDouble :: Double -> Double
895 sinhDouble, coshDouble, tanhDouble :: Double -> Double
896 expDouble (D# x) = D# (expDouble# x)
897 logDouble (D# x) = D# (logDouble# x)
898 sqrtDouble (D# x) = D# (sqrtDouble# x)
899 sinDouble (D# x) = D# (sinDouble# x)
900 cosDouble (D# x) = D# (cosDouble# x)
901 tanDouble (D# x) = D# (tanDouble# x)
902 asinDouble (D# x) = D# (asinDouble# x)
903 acosDouble (D# x) = D# (acosDouble# x)
904 atanDouble (D# x) = D# (atanDouble# x)
905 sinhDouble (D# x) = D# (sinhDouble# x)
906 coshDouble (D# x) = D# (coshDouble# x)
907 tanhDouble (D# x) = D# (tanhDouble# x)
909 powerDouble :: Double -> Double -> Double
910 powerDouble (D# x) (D# y) = D# (x **## y)
914 foreign import ccall unsafe "__encodeFloat"
915 encodeFloat# :: Int# -> ByteArray# -> Int -> Float
916 foreign import ccall unsafe "__int_encodeFloat"
917 int_encodeFloat# :: Int# -> Int -> Float
920 foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int
921 foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int
922 foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int
923 foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int
926 foreign import ccall unsafe "__encodeDouble"
927 encodeDouble# :: Int# -> ByteArray# -> Int -> Double
929 foreign import ccall unsafe "isDoubleNaN" isDoubleNaN :: Double -> Int
930 foreign import ccall unsafe "isDoubleInfinite" isDoubleInfinite :: Double -> Int
931 foreign import ccall unsafe "isDoubleDenormalized" isDoubleDenormalized :: Double -> Int
932 foreign import ccall unsafe "isDoubleNegativeZero" isDoubleNegativeZero :: Double -> Int
935 %*********************************************************
937 \subsection{Coercion rules}
939 %*********************************************************
943 "fromIntegral/Int->Float" fromIntegral = int2Float
944 "fromIntegral/Int->Double" fromIntegral = int2Double
945 "realToFrac/Float->Float" realToFrac = id :: Float -> Float
946 "realToFrac/Float->Double" realToFrac = float2Double
947 "realToFrac/Double->Float" realToFrac = double2Float
948 "realToFrac/Double->Double" realToFrac = id :: Double -> Double
949 "realToFrac/Int->Double" realToFrac = int2Double -- See Note [realToFrac int-to-float]
950 "realToFrac/Int->Float" realToFrac = int2Float -- ..ditto
954 Note [realToFrac int-to-float]
955 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
956 Don found that the RULES for realToFrac/Int->Double and simliarly
957 Float made a huge difference to some stream-fusion programs. Here's
960 import Data.Array.Vector
965 let c = replicateU n (2::Double)
966 a = mapU realToFrac (enumFromToU 0 (n-1) ) :: UArr Double
967 print (sumU (zipWithU (*) c a))
969 Without the RULE we get this loop body:
971 case $wtoRational sc_sY4 of ww_aM7 { (# ww1_aM9, ww2_aMa #) ->
972 case $wfromRat ww1_aM9 ww2_aMa of tpl_X1P { D# ipv_sW3 ->
976 (+## sc2_sY6 (*## 2.0 ipv_sW3))
983 (+## sc2_sXV (*## 2.0 (int2Double# sc_sXT)))
985 The running time of the program goes from 120 seconds to 0.198 seconds
986 with the native backend, and 0.143 seconds with the C backend.
988 A few more details in Trac #2251, and the patch message
989 "Add RULES for realToFrac from Int".
991 %*********************************************************
995 %*********************************************************
998 showSignedFloat :: (RealFloat a)
999 => (a -> ShowS) -- ^ a function that can show unsigned values
1000 -> Int -- ^ the precedence of the enclosing context
1001 -> a -- ^ the value to show
1003 showSignedFloat showPos p x
1004 | x < 0 || isNegativeZero x
1005 = showParen (p > 6) (showChar '-' . showPos (-x))
1006 | otherwise = showPos x