python:numpy.random模块生成随机数

这篇博客介绍了numpy.random模块在Python中生成随机数的方法,包括按均匀分布的rand、uniform、randint,按正态分布的randn、normal,以及随机排列数组的permutation和shuffle,还探讨了自定义概率分布抽样的choice方法。
摘要由CSDN通过智能技术生成

简介

所谓生成随机数,即按照某种概率分布,从给定的区间内随机选取一个数。常用的分布有:均匀分布(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)

结果:与均匀分布一致。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值