Round Function在v2.6.6中不起作用,但适用于v3.4.2

com*_*tea 2 python python-2.x python-3.x

我的round函数在linux python 2.6.6中不起作用,而在使用以下类型的代码后它在Windows 3.4.2中工作正常:

Array[i] = round(math.e ** AnotherArray[i], 4)

v.3.4.2:  0.0025999999999999999 => 0.0026
v.2.6.6:  0.0025999999999999999 =>  0.0025999999999999999
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 8

他们都工作相同,但是Python 2.7和最多将圆浮点数字印刷的时候representations,为了不被(语言和机器无关)迷惑用户,浮点运算的局限性.

十进制数0.0026不能完全表示为二进制数float,因此总会出现一些舍入错误.

如果你想减少混乱,只print需要数字:

>>> a = 0.0025999999999999999
>>> b = round(a,5)
>>> b                  # this calls repr(b) 
0.0025999999999999999
>>> print b            # this calls str(b)
0.0026
Run Code Online (Sandbox Code Playgroud)

在实践中,尽管你需要了解它们,但这些舍入错误很少发生,尤其是在比较相等时.

以下循环不会在0处停止:

x = 1.0
while x != 0:
    print x
    x -= 0.1
Run Code Online (Sandbox Code Playgroud)

为什么?让我们来看看:

>>> 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
Run Code Online (Sandbox Code Playgroud)

因此,始终考虑sys.float_info.epsilon到:

>>> 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
Run Code Online (Sandbox Code Playgroud)