Round Function 在 v2.6.6 中不起作用,但在 v3.4.2 中有效 [英] Round Function does not work in v2.6.6, but works in v3.4.2
问题描述
我的 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.0026v.2.6.6:0.0025999999999999999 =>0.0025999999999999999
它们的工作原理相同,但 Python 2.7 及更高版本在打印它们的 repr
esentations 时会舍入浮点数,为了不让用户被(独立于语言和机器的)浮点运算的限制一>.
十进制数0.0026
不能完全表示为二进制float
,所以总会有一些舍入误差.
如果你想减少混淆,只需打印
数字:
实际上,这些舍入误差很少有影响,尽管您需要注意它们,尤其是在比较相等性时.
以下循环不会在 0 处停止:
x = 1.0而 x != 0:打印 xx -= 0.1
为什么?一起来看看:
<预><代码>>>>x = 1.0>>>而 x != 0:... 打印 repr(x)... x -= 0.1...如果 x<0:中断...1.00.900000000000000020.800000000000000040.700000000000000070.600000000000000090.500000000000000110.400000000000000130.300000000000000160.200000000000000150.100000000000000141.3877787807814457e-16因此,请始终将sys.float_info.epsilon
考虑在内:
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
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
这篇关于Round Function 在 v2.6.6 中不起作用,但在 v3.4.2 中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!