Python numpy.linspace
numpy.linspace 函数用于在指定区间内创建一组均匀间隔的数字。
语法
numpy.linspace(start, stop, num = 50, endpoint = True/False, retstep = False/True, dtype = None)
参数
该函数可以接受以下参数:
- start − 序列的起始位置;默认情况下,被认为是零。
-
stop − 序列的结束位置。
-
num − 在起始位置和结束位置之间要生成的元素数量。
-
endpoint − 它控制是否包含结束位置的值在输出数组中。如果endpoint为True,则将stop参数作为nd.array的最后一项包含在内。如果endpoint为False,则不包含stop参数。
-
retstep − 如果retstep为True,则返回样本和步长。默认情况下,该值为False。
-
dtype − 它描述输出数组的类型。
示例1
让我们考虑以下示例:
# Import numpy library
import numpy as np
# linspace() function
x = np.linspace(start = 1, stop = 20, num = 10)
# round off the result
y = np.round(x)
print ("linspace of X :\n", y)
输出
它将生成如下输出 −
linspace of X :
[ 1. 3. 5. 7. 9. 12. 14. 16. 18. 20.]
示例2
np.arange 的工作方式与 np.linspace 类似,但有一点区别。
- np.linspace 使用计数来决定你在范围的最小值和最大值之间要获得多少个值。
-
np.arange 使用步长值来获得一组均匀间隔的值。
以下示例突出了这两种方法之间的差异。
# Import the required library
import numpy as np
# np.arange
A = np.arange(0, 20, 2)
print ("Elements of A :\n", A)
# np.linspace
B = np.linspace(0, 20, 10)
B = np.round(B)
print ("Elements of B :\n", B)
输出
它将生成以下输出 –
Elements of A :
[ 0 2 4 6 8 10 12 14 16 18]
Elements of B :
[ 0. 2. 4. 7. 9. 11. 13. 16. 18. 20.]