Python3 rounding to nearest even

折月煮酒 提交于 2019-12-18 12:53:00

问题


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?


回答1:


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.




回答2:


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



回答3:


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

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


来源:https://stackoverflow.com/questions/23248489/python3-rounding-to-nearest-even

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!