Is there an official specification for the round
function in Haskell? In GHCi version 7.0.3 I see the following behaviour:
ghci> round (0.5 :: Double) 0 ghci> round (1.5 :: Double) 2
Since both 0.5 and 1.5 are representable exactly as floating point numbers, I expected to see the same behaviour as in Python:
>>> round(0.5) 1.0 >>> round(1.5) 2.0
Is there a rationale for the difference, or is it a quirk of GHCi?
To round a number to the nearest whole number, you have to look at the first digit after the decimal point. If this digit is less than 5 (1, 2, 3, 4) we don't have to do anything, but if the digit is 5 or greater (5, 6, 7, 8, 9) we must round up.
Rounding a number involves replacing the number with an approximation of the number that results in a shorter, simpler, or more explicit representation of said number based on specific rounding definitions. For example, if rounding the number 2.7 to the nearest integer, 2.7 would be rounded to 3.
ceil(). To round down to the nearest integer, use math. floor(). To round a number to a number of decimals, give the round() function a second argument.
It's in the specification. You can see it in section 6.4.6 of the Haskell report:
round x
returns the nearest integer tox
, the even integer ifx
is equidistant between two integers.
As pointed out by @dflemstr, this is in accordance with the IEEE Standard for Floating-Point Arithmetic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With