linspace
是 NumPy 库中的一个函数,用于生成具有指定数量的等间距样本的数组。它的名字来源于“linear space”(线性空间),因为它在指定的范围内均匀地生成数值。
linspace
函数的基本语法如下:
(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
参数说明:
-
start
:序列的起始值。 -
stop
:序列的结束值。如果endpoint
为 True,该值会包含在生成的数组中;如果为 False,则不包含。 -
num
:要生成的样本数,默认为 50。 -
endpoint
:如果为 True,stop
是最后一个样本;否则,不包含stop
。默认为 True。[注意:step=(stop-start)/num] -
retstep
:如果为 True,返回 (samples
,step
),其中step
是样本之间的间隔。默认为 False。 -
dtype
:输出数组的数据类型。如果没有给出,则从其他输入参数推断数据类型。 -
axis
:在 0 的情况下,返回的数组是 1-D 的,否则返回的数组的形状是(num,) + shape(start)
。
下面是一些使用 linspace
的示例:
1基本用法
import numpy as np
# 生成从 0 到 10 的 5 个等间距的数
arr = (0, 10, 5)
print(arr)
输出结果:
[ 0. 2.5 5. 7.5 10. ]
2不包括结束值
# 生成从 0 到 10 的 5 个等间距的数,但不包括 10
arr = (0, 10, 5, endpoint=False)
print(arr)
输出结果:
[0. 2. 4. 6. 8.]
3返回步长
# 生成从 0 到 10 的 5 个等间距的数,并返回步长
samples, step = (0, 10, 5, retstep=True)
print(samples)
print(step)
输出结果:
[ 0. 2.5 5. 7.5 10. ] 2.5
4在多维数组中使用
# 假设我们有一个二维数组,我们想要在每个子数组上应用 linspace
start = ([0, 1, 2])
arr_2d = (start, 10, 5, axis=0)
print(arr_2d)
输出结果:
[[ 0. 1. 2. ] [ 2.5 3.25 4. ] [ 5. 5.5 6. ] [ 7.5 7.75 8. ] [10. 10. 10. ]]
在这个例子中,linspace
在 start
数组和 10 之间生成了 5 个等间距的数,并将这些数沿着第一个轴(axis=0
)排列成一个二维数组。
5自定义数据类型
你可以通过dtype
参数来指定输出数组的数据类型。
import numpy as np
# 生成从 0 到 10 的 5 个等间距的数,数据类型为整数
arr = (0, 10, 5, dtype=int)
print(arr)
输出结果:
[ 0 2 5 7 10]
请注意,当使用整数类型时,由于舍入,生成的数值可能不是完全等间距的。
6在非一维数组上使用
虽然linspace
主要用于生成一维数组,但你可以通过与其他NumPy函数结合使用来在非一维数组上应用它。
import numpy as np
# 创建一个二维数组的每一行都使用linspace
rows = 3
num_points = 4
arr_2d = ([(i, i+10, num_points) for i in range(rows)])
print(arr_2d)
输出结果:
[[ 0. 3.33333333 6.66666667 10. ] [ 1. 4.33333333 7.66666667 11. ] [ 2. 5.33333333 8.66666667 12. ]]
在这个例子中,我们使用列表推导式来创建一个二维数组,其中每一行都是使用linspace
函数生成的一维数组。
注意事项
- 当
endpoint
参数为False
时,生成的数组将不包含结束值。 -
retstep
参数允许你获取生成数组时使用的步长。 -
dtype
参数允许你指定输出数组的数据类型。 - 虽然
linspace
通常用于生成一维数组,但它可以与其他NumPy函数结合使用来生成更复杂的数组结构。
2024年4月1日学习补充:step=(stop-start)/num]
例:
(0,10,11,endpoint=False)
start=0 ; stop=10 ; num=11 step=(10-0)/11=0.90909090909090
array([0. , 0.90909091, 1.81818182, 2.72727273, 3.63636364, 4.54545455, 5.45454545, 6.36363636, 7.27272727, 8.18181818, 9.09090909])