假设我想生成一个介于 0 和 1 之间、间距为 0.1 的数组。在 R 中,我们可以这样做
> seq(0, 1, 0.1)
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
在 Python 中,由于 numpy.arange
不包含右端,因此我需要在 stop
中添加少量内容。
np.arange(0, 1.01, 0.1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
但这似乎有点奇怪。是否可以强制 numpy.arange 包含右端?或者也许其他一些功能可以做到这一点?
最佳答案
对于浮点步骤,您应该非常小心地使用arange
。
From the docs :
When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases.
相反,请使用linspace
,它允许您指定返回值的确切数量。
>>> np.linspace(0, 1, 11)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
linspace
也实际上允许您指定是否包含端点(默认情况下True
):
>>> np.linspace(0, 1, 11, endpoint=True)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0, 1, 11, endpoint=False)
array([0. , 0.09090909, 0.18181818, 0.27272727, 0.36363636,
0.45454545, 0.54545455, 0.63636364, 0.72727273, 0.81818182,
0.90909091])
关于python - 使用 NumPy.arange 生成包括右端在内的等距值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59777735/