基于数值范围创建函数创建ndarray
1 numpy.arange
arange([start=0,] stop[, step=1,][, dtype=None])
>>> np.arange(3) array([0, 1, 2]) >>> np.arange(3.0) array([ 0., 1., 2.]) >>> np.arange(3,7) array([3, 4, 5, 6]) >>> np.arange(3,7,2) array([3, 5])
2 numpy.linspace
linspace(start, stop[, num=50, endpoint=True, retstep=False,dtype=None])
与arange()相似,指定了范围间的均有间隔数量
start - 序列的起始值
stop - 序列的终止值,如果 endpoint 为 True ,该值包含于序列中
num - 生成等间隔样例数量,默认50
endpoint - 序列中是否包含 stop 数量,默认True
retstep - 如果为True,以(样例samples, 步长step)元组格式返回数据
dtype - 数据类型,默认为float
import numpy as np a = np.linspace(2,3,num=3) print(a) #[2. 2.5 3. ] b = np.linspace(2,3,num=3,endpoint=False) print(b) #[2. 2.33333333 2.66666667] b = np.linspace(2,3,num=3,retstep=True) print(b) #(array([2. , 2.5, 3. ]), 0.5)
图解说明:
import numpy as np 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()
运行
3 numpy.logspace
logspace(start, stop[, num=50, endpoint=True, base=10.0,dtype=None])
均匀返回基于对数刻度尺的数字
start - 起始值,base ** start
stop - 终止值,base ** stop
num - 范围内数值的数量,默认为50
endpoint - 是否包含终止值,默认True(包含终止值)
base - 对数空间的底数,默认为 10
dtype - 返回数据类型,当 dtype = None 时,返回值数据类型取决于其他输入参数
import numpy as np a = np.logspace(2.0,3.0,num=3) print(a) #[ 100. 316.22776602 1000. ] b = np.logspace(1,4,num=3,base=2) print(b) #[ 2. 5.65685425 16. ] c = np.logspace(1,4,num=4,base=2) print(c) #[ 2. 4. 8. 16.]
对数感觉像是指数函数。
参考:NumPy来自数值范围的数组 和 NumPy Reference(Release 1.14.5) 3.1.5 Numerical ranges P431