Python – numpy.linspace


numpy.linspace 函式可用於建立已定義區間內的均勻分佈數字集合。

語法

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

引數

該函式可接受以下引數 −

  • start − 序列的開頭;預設為零。

  • stop − 序列的結尾。

  • num − start 和 stop 之間要生成元素的數量。

  • endpoint − 確定在輸出陣列中包含還是不包含 stop 值。如果 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.]

更新於:03-Mar-2022

2K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.