python - 使用 NumPy.arange 生成包括右端在内的等距值

标签 python numpy

假设我想生成一个介于 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 包含右端?或者也许其他一些功能可以做到这一点?

最佳答案

对于浮点步骤,您应该非常小心地使用arangeFrom 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/

相关文章:

python - 第一次出现大于 numpy 数组中给定值的值

python - 向量化内存函数

python - wxpython GridBagSizer问题

PHP bcmath 与 Python Decimal

python - 如何找到分位数的索引

python - 将映射数组应用于 numpy 数组中的所有元素的快速方法?

numpy - 如何使用 NumPy 在 Python 中按行应用均方误差而不循环

python - 将自定义类转换为标准 Python 类型

python - Django操作错误 'no such column:' sqlite

python - GTK 中的 matplotlib 图和工具