NumPy linspace()

linspace() 方法在给定区间内创建具有等间隔元素的数组。

示例

import numpy as np

# create an array with 3 elements between 5 and 10 array1 = np.linspace(5, 10, 3)
print(array1) # Output: [ 5. 7.5 10. ]

linspace() 语法

linspace() 的语法是:

numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None, axis = 0)

linspace() 参数

linspace() 方法接受以下参数:

  • start - 序列的起始值,默认值为 **0** (可以是 array_like)
  • stop - 序列的结束值 (可以是 array_like)
  • num (可选) - 要生成的样本数量 (int)
  • endpoint (可选) - 指定是否包含结束值 (bool)
  • retstep (可选) - 如果为 True,则返回样本之间的步长 (bool)
  • dtype(可选)- 输出数组的类型
  • axis (可选) - 结果中存储样本的轴 (int)

注意事项:

  • step 不能为零。否则,您将收到 ZeroDivisionError
  • 如果省略 dtypelinspace() 将根据其他参数的类型来确定数组元素的类型。
  • linspace() 中,stop 值是包含在内的。

linspace() 返回值

linspace() 方法返回一个包含等间隔值的数组。

注意:如果 retstepTrue,它还将返回步长,即两个元素之间的间隔。


示例 1:使用 linspace 创建一维数组

import numpy as np
 
# create an array of 5 elements between 2.0 and 3.0 array1 = np.linspace(2.0, 3.0, num=5)
print("Array1:", array1)
# create an array of 5 elements between 2.0 and 3.0 excluding the endpoint array2 = np.linspace(2.0, 3.0, num=5, endpoint=False)
print("Array2:", array2)
# create an array of 5 elements between 2.0 and 3.0 with the step size included array3, step_size = np.linspace(2.0, 3.0, num=5, retstep=True)
print("Array3:", array3) print("Step Size:", step_size)

输出

Array1: [2.   2.25 2.5  2.75 3.  ]
Array2: [2.  2.2 2.4 2.6 2.8]
Array3: [2.   2.25 2.5  2.75 3.  ]
Step Size: 0.25

示例 2:使用 linspace 创建 n 维数组

import numpy as np
 
# create an array of 5 elements between [1, 2] and [3, 4] array1 = np.linspace([1, 2], [3, 4], num=5)
print("Array1:") print(array1)
# create an array of 5 elements between [1, 2] and [3, 4] along axis 1 array2 = np.linspace([1, 2], [3, 4], num=5, axis=1)
print("\nArray2:") print(array2)

输出

Array1:
[[1.  2. ]
 [1.5 2.5]
 [2.  3. ]
 [2.5 3.5]
 [3.  4. ]]

Array2:
[[1.  1.5 2.  2.5 3. ]
 [2.  2.5 3.  3.5 4. ]]

arange 和 linspace 的主要区别

np.arange()np.linspace() 都是用于生成数值序列的 NumPy 函数,但它们在行为上有一些不同。

  • arange() 以给定的 step 大小从 startstop 生成一个值序列,而 linspacestartstop 生成 num 个等间隔值的序列。
  • arange() 不包含 stop 值,而 linspace 包含 stop 值,除非通过 endpoint = False 指定。

让我们看一个例子。

import numpy as np

# elements between 10 and 40 with stepsize 4 array1 = np.arange(10, 50 , 4) # generate 4 elements between 10 and 40 array2 = np.linspace(10, 50 , 4)
print('Using arange:', array1) # doesn't include 50 print('Using linspace:', array2) #includes 50

输出

Using arange: [10 14 18 22 26 30 34 38 42 46]
Using linspace: [10.         23.33333333 36.66666667 50.        ]

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战