Python numpy.linspace的浮点数行为异常

时间:2018-08-29 12:06:41

标签: python numpy

我遇到numpy linspace问题

import numpy as np

temp = np.linspace(1,2,11)

for t in temp:
    print(t)

此返回:

1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7000000000000002
1.8
1.9
2.0

1.7值肯定是错误的。

似乎与此问题https://github.com/numpy/numpy/issues/8909

有关

有人有没有遇到过numpy.linspace这样的问题?这是一个已知问题吗?

François

1 个答案:

答案 0 :(得分:2)

这与numpy无关,请考虑:

>>> temp = np.linspace(1,2,11)
>>> temp
array([1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. ])
>>> #                                     ^ look, numpy displays it fine
>>> for t in temp:
...     print(t)
... 
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7000000000000002
1.8
1.9
2.0

“问题”与计算机通常表示浮点数的方式有关。参见:https://docs.python.org/3/tutorial/floatingpoint.html