numpy.linspace#
- numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, *, device=None)[source]#
在指定區間內傳回均勻間隔的數字。
傳回在區間 [start, stop] 內計算的 num 個均勻間隔樣本。
區間的端點可以選擇性地排除。
Changed in version 1.20.0: Values are rounded towards
-inf
instead of0
when an integerdtype
is specified. The old behavior can still be obtained withnp.linspace(start, stop, num).astype(int)
- 參數:
- startarray_like
序列的起始值。
- stoparray_like
序列的終止值,除非 endpoint 設定為 False。在這種情況下,序列由
num + 1
個均勻間隔樣本中除了最後一個之外的所有樣本組成,因此 stop 會被排除。請注意,當 endpoint 為 False 時,步長大小會改變。- numint, optional
要產生的樣本數量。預設值為 50。必須為非負數。
- endpointbool, optional
若為 True,則 stop 是最後一個樣本。否則,不包含在內。預設值為 True。
- retstepbool, optional
若為 True,則傳回 (samples, step),其中 step 是樣本之間的間距。
- dtypedtype, optional
輸出陣列的型別。如果未給定
dtype
,則資料型別會從 start 和 stop 推斷而來。推斷的 dtype 永遠不會是整數;即使參數會產生整數陣列,也會選擇 float。- axisint, optional
結果中用於儲存樣本的軸。僅當 start 或 stop 為 array-like 時才相關。預設情況下 (0),樣本將沿著在開頭插入的新軸排列。使用 -1 可在末尾取得軸。
- devicestr, optional
放置建立的陣列的裝置。預設值:None。僅用於 Array-API 互操作性,因此如果傳遞,則必須為
"cpu"
。在版本 2.0.0 中新增。
- 傳回值:
- samplesndarray
在閉區間
[start, stop]
或半開區間[start, stop)
中有 num 個均勻間隔的樣本(取決於 endpoint 是 True 還是 False)。- stepfloat, optional
僅在 retstep 為 True 時傳回
樣本之間間距的大小。
另請參閱
範例
>>> import numpy as np >>> np.linspace(2.0, 3.0, num=5) array([2. , 2.25, 2.5 , 2.75, 3. ]) >>> np.linspace(2.0, 3.0, num=5, endpoint=False) array([2. , 2.2, 2.4, 2.6, 2.8]) >>> np.linspace(2.0, 3.0, num=5, retstep=True) (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
圖形化說明
>>> import matplotlib.pyplot as plt >>> N = 8 >>> y = np.zeros(N) >>> x1 = np.linspace(0, 10, N, endpoint=True) >>> x2 = np.linspace(0, 10, N, endpoint=False) >>> plt.plot(x1, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show()