Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

To answer the title... If you use int(n), it truncates towards zero. If the result is odd, then you add one:

n = 2.7     # your whatever float
result = int(n)
if (result & 1):     
    result += 1

Update: Yes, there is a bug for negative numbers. And there is also a bug for numbers that already have an integer value. Homework for you. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top