问题
My round function does not work in linux python 2.6.6, whereas it works fine in Windows 3.4.2 after using the following type of code:
Array[i] = round(math.e ** AnotherArray[i], 4)
v.3.4.2: 0.0025999999999999999 => 0.0026
v.2.6.6: 0.0025999999999999999 => 0.0025999999999999999
回答1:
They both work the same, but Python 2.7 and up will round floating point numbers when printing their repr
esentations, in order to not confuse users by the (language- and machine-independent) limitations of floating point arithmetic.
The decimal number 0.0026
can't be represented exactly as a binary float
, so there will always be some rounding error.
If you want less confusion, just print
the numbers:
>>> a = 0.0025999999999999999
>>> b = round(a,5)
>>> b # this calls repr(b)
0.0025999999999999999
>>> print b # this calls str(b)
0.0026
In practice, those rounding errors rarely matter, although you need to be aware of them, especially when comparing for equality.
The following loop doesn't stop at 0:
x = 1.0
while x != 0:
print x
x -= 0.1
Why? Let's take a look:
>>> x = 1.0
>>> while x != 0:
... print repr(x)
... x -= 0.1
... if x<0: break
...
1.0
0.90000000000000002
0.80000000000000004
0.70000000000000007
0.60000000000000009
0.50000000000000011
0.40000000000000013
0.30000000000000016
0.20000000000000015
0.10000000000000014
1.3877787807814457e-16
Therefore, always take sys.float_info.epsilon
into account:
>>> x = 1.0
>>> while abs(x) > sys.float_info.epsilon:
... print x
... x -= 0.1
...
1.0
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
来源:https://stackoverflow.com/questions/27214184/round-function-does-not-work-in-v2-6-6-but-works-in-v3-4-2