Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 rounding to nearest even

Python3.4 rounds to the nearest even (in the tie-breaker case).

>>> round(1.5)
2
>>> round(2.5)
2

But it only seems to do this when rounding to an integer.

>>> round(2.75, 1)
2.8
>>> round(2.85, 1)
2.9

In the final example above, I would have expected 2.8 as the answer when rounding to the nearest even.

Why is there a discrepancy between the two behaviors?

like image 398
Alex Couper Avatar asked Apr 23 '14 15:04

Alex Couper


People also ask

Why does Python round even numbers down?

In Python, if the fractional component of the number is halfway between two integers, one of which is even and the other odd, then the even number is returned. This kind of rounding is called rounding to even (or banker's rounding).

How do I set rounding in Python?

To round to the nearest whole number in Python, you can use the round() method. You should not specify a number of decimal places to which your number should be rounded. Our Python code returns: 24. The round() function is usually used with floating-point numbers, which include decimal places.

Is there a rounding function in Python?

Python round() Function The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.


2 Answers

Floating point numbers are only approximations; 2.85 cannot be represented exactly:

>>> format(2.85, '.53f')
'2.85000000000000008881784197001252323389053344726562500'

It is slightly over 2.85.

0.5 and 0.75 can be represented exactly with binary fractions (1/2 and 1/2 + 1/4, respectively).

The round() function documents this explicitly:

Note: The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

like image 70
Martijn Pieters Avatar answered Oct 17 '22 11:10

Martijn Pieters


Martijn got it exactly right. If you want an int-rounder to round to the nearest even, then I would go with this:

def myRound(n):
    answer = round(n)
    if not answer%2:
        return answer
    if abs(answer+1-n) < abs(answer-1-n):
        return answer + 1
    else:
        return answer - 1
like image 43
inspectorG4dget Avatar answered Oct 17 '22 11:10

inspectorG4dget