Being a sequence generator, the numpy.linspace()
function is used to generate a sequence of numbers in linear space with a uniform step size.
作为序列生成器, numpy.linspace()
函数用于在线性空间中以均匀步长生成数字序列。
Numpy generally can generate sequences using numpy.arange()
, but when we use floating-point arguments, it can result in a loss of precision, which may cause an unpredictable output.
Numpy通常可以使用numpy.arange()
生成序列,但是当我们使用浮点参数时,可能会导致精度损失,这可能会导致不可预测的输出。
To avoid any potential loss of precision due to the floating-point precision, numpy provides us with a separate sequence generator in numpy.linspace()
, which is the preferred option if you already know the number of elements you need. But you generally get the same output using both linspace()
and arange()
with appropriate parameters, so both can be chosen for the same task.
为了避免由于浮点精度而造成的任何精度损失,numpy在numpy.linspace()
为我们提供了一个单独的序列生成器,如果您已经知道所需的元素数,则这是首选。 但是通常使用带有适当参数的linspace()
和arange()
可以得到相同的输出,因此可以为同一任务选择两者。
For example, the following code plots 2 linear sequences between 0 and 10 using numpy.linspace()
to show that there is uniformity generated by the sequence.
例如,以下代码使用numpy.linspace()
在0到10之间绘制2个线性序列,以显示该序列生成的均匀性。
import numpy as np
import matplotlib.pyplot as plt
y = np.zeros(5)
x1 = np.linspace(0, 10, 5)
x2 = np.linspace(0, 10, 5)
plt.plot(x1, y, 'o')
plt.plot(x2, y + 0.5, 'o')
plt.ylim([-0.5, 1])
plt.show()
Output:
输出 :