<分区>
我是 python 的新手,我试过这个:
import numpy as np
x = np.arange(0.7,1.3,0.1)
print (x)
y = np.arange(0.6,1.3,0.1)
print (y)
输出为 [ 0.7 0.8 0.9 1. 1.1 1.2 1.3]
和 [ 0.6 0.7 0.8 0.9 1. 1.1 1.2]
。为什么在第一种情况下 1.3 出现在列表中而在第二种情况下却没有?
标签 python
<分区>
我是 python 的新手,我试过这个:
import numpy as np
x = np.arange(0.7,1.3,0.1)
print (x)
y = np.arange(0.6,1.3,0.1)
print (y)
输出为 [ 0.7 0.8 0.9 1. 1.1 1.2 1.3]
和 [ 0.6 0.7 0.8 0.9 1. 1.1 1.2]
。为什么在第一种情况下 1.3 出现在列表中而在第二种情况下却没有?
最佳答案
这是由于 rounding errors .如果您实际以全精度打印 x
中的最后一个元素,您会看到它小于 1.3
:
>>> import numpy as np
>>> x = np.arange(0.7,1.3,0.1)
>>> 1.3 > x[-1]
True
>>> x[-1]
1.2999999999999998
请注意,如 documentation 中所述
When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use
linspace
for these cases.:
关于python - Python 中的列表最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235246/