Round to nearest integer strange results

14,860

It's in the specification. You can see it in section 6.4.6 of the Haskell report:

round x returns the nearest integer to x, the even integer if x is equidistant between two integers.

As pointed out by @dflemstr, this is in accordance with the IEEE Standard for Floating-Point Arithmetic.

Share:
14,860

Related videos on Youtube

Chris Taylor
Author by

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, 2022

Comments

  • Chris Taylor
    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
      Mark Dickinson almost 12 years
      Note that Python 3 behaves in the same way as GHCi here.
    • Chris Taylor
      Chris Taylor almost 12 years
      I 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
      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
      amr over 11 years
      It'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
    dflemstr almost 12 years
    This is according to the IEEE 754 floating point rounding mode standard.
  • Poindexter
    Poindexter almost 12 years
    Here's the code for round if anyone is interested: hackage.haskell.org/packages/archive/base/latest/doc/html/sr‌​c/… the check for even is quite obvious there.
  • janneb
    janneb almost 12 years
    FWIW, 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
    SwiftsNamesake over 6 years
    @Poindexter The link is dead. Long live the link!