python numpy arange: strange behavior [duplicate]

爷,独闯天下 提交于 2021-02-20 01:34:46

问题


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

In both cases, the array gets to 1.12... how would you explain that?


回答1:


Because of floating point error, 1.1, 0.01 and 0.12 are not as precise as one might expect, nor are mathematical operations between them. For example:

>>> 1.1 + 0.01 + 0.01 + 0.01
1.1300000000000001

See also:

>>> decimal.Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> decimal.Decimal(1.12)
Decimal('1.12000000000000010658141036401502788066864013671875')

If they were precise, np.arange(1.1, 1.12, 0.01) would be array([1.1 , 1.11])

np.arange specification mentions that as well: For the stop argument it writes:

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.

You can avoid the problem by always specifying an upper limit which is between two steps, rather than exactly on the boundary:

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


来源:https://stackoverflow.com/questions/50655175/python-numpy-arange-strange-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!