简介
所谓生成随机数,即按照某种概率分布,从给定的区间内随机选取一个数。常用的分布有:均匀分布(uniform distribution),正态分布(normal distribution),泊松分布(poisson distribution)等。
python中的numpy.random模块提供了常用的随机数生成方法,下面简要总结。
按均匀分布生成随机数
rand
功能
按照均匀分布,在[0,1)内生成随机数。
接口
Docstring:
rand(d0, d1, ..., dn)
Random values in a given shape.
Create an array of the given shape and populate it with
random samples from a uniform distribution
over ``[0, 1)``.
实例
In [3]: np.random.rand()
Out[3]: 0.08621180209775481
In [4]: np.random.rand(5)
Out[4]: array([0.85086433, 0.46726857, 0.48144885, 0.36369815, 0.9181539 ])
In [5]: np.random.rand(2,5)
Out[5]:
array([[0.70784333, 0.08966827, 0.50090152, 0.22517888, 0.86735194],
[0.92224362, 0.98468415, 0.19134583, 0.06757754, 0.19330571]])
验证下是按均匀分布生成的随机数
方法:利用直方图可验证其概率密度函数是否与均匀分布一致。
x = np.random.rand(10000)
plt.hist(x,bins=20,density=True)
结果:符合均匀分布的概率密度函数,即P(x)=1, x=[0,1]
uniform
功能
按照均匀分布,在[low,high)内生成随机数。
接口
Docstring:
uniform(low=0.0, high=1.0, size=None)
Draw samples from a uniform distribution.
Samples are uniformly distributed over the half-open interval
``[low, high)`` (includes low, but excludes high). In other words,
any value within the given interval is equally likely to be drawn
by `uniform`.
实例
In [8]: np.random.uniform(-1,1)
Out[8]: -0.34092928027362945
In [9]: np.random.uniform(-1,1,5)
Out[9]: array([ 0.84319637, -0.00449745, -0.21958133, -0.16755161, -0.94383758])
In [10]: np.random.uniform(-1,1,(2,5))
Out[10]:
array([[-0.66176972, 0.71703011, 0.61658043, 0.0373402 , 0.95824383],
[ 0.31743693, 0.48948276, 0.0393428 , 0.64896449, 0.3659116 ]])
验证下是按均匀分布生成的随机数
x = np.random.uniform(-1,1,10000)
plt.hist(x,bins=20,density=True)
结果:与均匀分布一致。