Rounding error in Python with non

I'm beginner in Python, and I have one question.
Why does rounding a number like 5.5, 7.5, (anything).5 with odd integer part applying round(num) work correctly (rule 5/4), but rounding number like (anything).5 with non-odd integer part by the same function returns just an integer part? (But if we add a little number like 0.000000001 to that decimal number it works correctly)

I mean the next:

round(9.5)

returns 10, and it's correct. But

round(8.5)

returns 8, and it isn't correct. And

round(8.5 + 0.0000000000001)

returns 9.

Why it works incorrect?
I use Python 3.2.2 at Windows.


Python 3.x, in contrast to Python 2.x, uses Banker's rounding for the round() function.

This is the documented behaviour:

[I]f two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).

Since floating point numbers by their very nature are only approximations, it shouldn't matter too much how "exact" half-integers are treated – there could always be rounding errors in the preceding calculations anyway.

Edit : To get the old rounding behaviour, you could use

def my_round(x):
    return int(x + math.copysign(0.5, x))
链接地址: http://www.djcxy.com/p/48410.html

上一篇: 在.net中,我如何选择Decimal和Double

下一篇: 使用非圆整Python中的错误