Round to nearest integer strange results
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.
Related videos on Youtube
Chris Taylor
I'm broadly interested in very applied math. I try to apply ideas from mathematics, statistics, machine learning, formal systems and computer science to solve real-world problems. Mostly in applied finance/quantitative trading, but in other areas if the mood takes me.
Updated on July 11, 2022Comments
-
Chris Taylor almost 2 years
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?
-
Mark Dickinson almost 12 yearsNote that Python 3 behaves in the same way as GHCi here.
-
Chris Taylor almost 12 yearsI suppose it makes it more likely that rounding errors will cancel out if you round a bunch of numbers and then sum them up...
-
Daniel Fischer almost 12 years@ChrisTaylor Yes, it's to avoid bias introduced by rounding. It's often called 'Banker's rounding' (though, iirc, in the EU, round-half-away-from-zero is mandatory for financial applications). With round-half-away-from-zero, it cancels out only if the values are half negative and half positive, with half-to-even, it cancels out more often.
-
amr over 11 yearsIt's my understanding that rounding to the even number is the scientific standard. Rounding up is common in grade school for some reason but is otherwise just another convention.
-
-
dflemstr almost 12 yearsThis is according to the IEEE 754 floating point rounding mode standard.
-
Poindexter almost 12 yearsHere's the code for
round
if anyone is interested: hackage.haskell.org/packages/archive/base/latest/doc/html/src/… the check for even is quite obvious there. -
janneb almost 12 yearsFWIW, for comparison, the python round() is a wrapper around the C99 round() function, which on an implementation that follows C99 Annex F rounds ties away from zero.
-
SwiftsNamesake over 6 years@Poindexter The link is dead. Long live the link!