python numpy arange : strange behavior

标签 python numpy

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.10.010.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/

相关文章:

python - 如何通过XPath跳转到下一页?

python - 我们如何才能更快地比较两个不同表之间的数据

python - 当前实现中如何避免索引超出范围错误?

python - 快速读取Python中的列分隔文本数据

python - 如何计算numpy中多个项目的出现次数?

python - 加速 numpy 嵌套循环

python - 如何对一维 numpy 数组进行下采样?

python - HSV2BGR 转换在 Python OpenCV 脚本中失败

python - 如何在启用 visual studio 环境的情况下运行 SublimeText

python - Python/numpy点列表到黑白图像区域