linspace的功能最初是从MATLAB中学来的,用来创建等差数列。
numpy.linspace
numpy.
linspace
(start, stop, num=50, endpoint=True, retstep=False, dtype=None)[source]
Return evenly spaced numbers over a specified interval.
Returns num evenly spaced samples, calculated over the interval [start, stop].
The endpoint of the interval can optionally be excluded.
Parameters: | start : scalar
stop : scalar
num : int, optional
endpoint : bool, optional
retstep : bool, optional
dtype : dtype, optional
|
---|---|
Returns: | samples : ndarray
step : float, optional
|
例:
1,print(np.linspace(1,100,20, dtype=int))
输出:
[ 1 6 11 16 21 27 32 37 42 47 53 58 63 68 73 79 84 89
94 100]
可以发现,上面的差有的是5,有的是6,和别的不一样
原因在于1-100分成20个的话,无法等分。
要想正好等分的话, 应该满足这样:
stop-start/num -1 为整数
上面的例子如果这样改,print(np.linspace(0,100,21, dtype=int, endpoint=True))
输出变成
[ 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100]
或者print(np.linspace(1,101,21, dtype=int, endpoint=True))
输出变成
[ 1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 101]
2,print(np.linspace(1,100,20, dtype=int, endpoint=False))
[ 1 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95]
endpoint=False,表示不包括stop的100,就是1-100之间的数,成分20份,但是最后一个数又要小于100