gpt4 book ai didi

python - Round Function 在 v2.6.6 中不起作用,但在 v3.4.2 中起作用

转载 作者:行者123 更新时间:2023-11-28 20:21:42 25 4
gpt4 key购买 nike

我的 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

最佳答案

它们的工作原理相同,但是 Python 2.7 及更高版本将在打印它们的representations 时舍入 float ,以免用户因(语言-和机器无关)limitations of floating point arithmetic .

十进制数 0.0026 无法精确表示为二进制 float,因此总会存在一些舍入误差。

如果你想减少混淆,只需打印数字:

>>> a = 0.0025999999999999999
>>> b = round(a,5)
>>> b # this calls repr(b)
0.0025999999999999999
>>> print b # this calls str(b)
0.0026

在实践中,这些舍入误差并不重要,但您需要注意它们,尤其是在比较相等性时。

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

x = 1.0
while x != 0:
print x
x -= 0.1

为什么?让我们来看看:

>>> 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

因此,请始终考虑 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

关于python - Round Function 在 v2.6.6 中不起作用,但在 v3.4.2 中起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27214184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com