python - Python 中的列表最后一个元素

标签 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/

相关文章:

python - 在 python 中执行 bash 脚本

python - 在类对象中存储未绑定(bind)的 python 函数

python - 将字符串写入文件的 pythonic 方式是什么?

python - 在现代 Python 中声明自定义异常的正确方法?

python - Django VirtualEnv 设置 - 'setuptools pip wheel failed with error code -11'

python - 生成器字典内的迭代变量

python - Python 中的证书存储库

javascript - 在多个表单集中使用 ajax 和 django

python - 将 mark_line 分层到交互式线图上会显着降低 Altair 的性能

python - 如何在Keras中实现CRelu?