问题
One half, i.e. 0.5 in decimal, has an exact binary representation: 0.1
Nevertheless, if I round it to integer, I get 0 instead of 1. I tried in Python and C, which behave the same. E.g. the python code:
>>> a,b,c = 0.49, 0.5, 0.51
>>> [round(x) for x in (a,b,c)]
[0, 0, 1]
>>> "%.0f %.0f %.0f" % (a,b,c)
'0 0 1'
Interestingly,
>>> a,b,c = 0.049, 0.05, 0.051
>>> [round(x,1) for x in (a,b,c)]
[0.0, 0.1, 0.1]
>>> "%.1f %.1f %.1f" % (a,b,c)
'0.0 0.1 0.1'
I am aware of Numerous similar questions, e.g. Python rounding error with float numbers, the Python tutorial on floating point arithmetics, and the obligatory What Every Computer Scientist Should Know About Floating-Point Arithmetic.
If a number has an exact binary representation, such as (decimal) 0.5, shouldn't it be rounded correctly?
edit: The issue occurs in version 3.4.3, but not in version 2.7.6
回答1:
I know they changed the round method in python 3.
So, under v2.7.3:
In [85]: round(2.5)
Out[85]: 3.0
In [86]: round(3.5)
Out[86]: 4.0
under v3.2.3:
In [32]: round(2.5)
Out[32]: 2
In [33]: round(3.5)
Out[33]: 4
I don't know if it helps you but I am posting it as answer since I can't comment due to my low reputation.
The question is answered more properly here : Python 3.x rounding behavior
来源:https://stackoverflow.com/questions/38099977/why-is-rounding-0-5-decimal-not-exact