Python 2.7.9 (default, Jun 29 2016, 13:08:31)
IPython 5.6.0 -- An enhanced Interactive Python.
In [1]: import numpy as np
In [2]: np.__version__
Out[2]: '1.14.3'
In [3]: np.arange(1.1, 1.12, 0.01)
Out[3]: array([1.1 , 1.11, 1.12])
In [4]: np.arange(1.1, 1.13, 0.01)
Out[4]: array([1.1 , 1.11, 1.12])
在这两种情况下,数组都达到 1.12...您如何解释?
最佳答案
由于浮点误差,1.1
、0.01
和 0.12
并不像人们想象的那么精确,它们之间的数学运算也不如人们想象的那么精确。例如:
>>> 1.1 + 0.01 + 0.01 + 0.01
1.1300000000000001
另请参阅:
>>> decimal.Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> decimal.Decimal(1.12)
Decimal('1.12000000000000010658141036401502788066864013671875')
如果它们是精确的,np.arange(1.1, 1.12, 0.01)
将是 array([1.1 , 1.11])
np.arange
规范也提到了这一点:对于 stop
参数,它写道:
stop : number
End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.
您可以通过始终指定两个步骤之间的上限来避免该问题,而不是精确地在边界上:
>>> np.arange(1.1, 1.115, 0.01)
array([1.1 , 1.11])
>>> np.arange(1.1, 1.125, 0.01)
array([1.1 , 1.11, 1.12])
>>> np.arange(1.1, 1.135, 0.01)
array([1.1 , 1.11, 1.12, 1.13])
关于python numpy arange : strange behavior,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50655175/