Python3 Random模块代码详解
描述
random()方法返回随机生成的一个实数,它在[0,1)范围内。
importrandom
help(random)
FUNCTIONS
betavariate(alpha,beta)methodofRandominstance#随机实例的方法
Betadistribution.#β分布
Conditionsontheparametersarealpha>0andbeta>0.#必须传入大于0的alpha与beta参数
Returnedvaluesrangebetween0and1.#返回一个0-1之间的值,这个值你是随机的!
a=random.betavariate(999999,99999999999999999)#第一次执行结果:9.995974671839104e-12第二次执行结果:1.0006927848540756e-11
贝塔分布(BetaDistribution)是一个作为伯努利分布和二项式分布的共轭先验分布的密度函数,在机器学习和数理统计学中有重要应用。
在概率论中,贝塔分布,也称Β分布,是指一组定义在(0,1)区间的连续概率分布。
choice(seq)methodofRandominstance
Choosearandomelementfromanon-emptysequence.#随机从一个不为空的序列中取出一个元素,参数必须不为空
Python包含6种内建的序列,包括列表、元组、字符串、Unicode字符串、buffer对象和xrange对象。
choices(population,weights=None,*,cum_weights=None,k=1)methodofRandominstance#随机实例的方法
Returnaksizedlistofpopulationelementschosenwithreplacement.#通过chosenwithreplacement(就是每次抽取的机会都是相同的或按权重来的,前面的选择不会影响后面选择的概率)的方式获取一个由k个元素组成的随机列表
Iftherelativeweightsorcumulativeweightsarenotspecified,#如果未指定相对权重或累积权重,
theselectionsaremadewithequalprobability.#则选择的概率相等。
从population中随机抽取k个元素(可重复)。两个参数不能同时存在。
示例:
print(random.choices(['red','black','green'],[18,18,2],k=6))#以18的概率权重取red,18的概率权重取black,2的概率权重取green,共进行6次
trial=lambda:random.choices('HT',cum_weights=(0.60,1.00),k=7).count('H')>=5#H的概率是0.6,T的概率是0.4
print(sum(trial()foriinrange(10000))/10000)
trial2=lambda:2500<=sorted(random.choices(range(10000),k=5))[2]<7500
print(sum(trial2()foriinrange(10000))/10000)
fromstatisticsimportmean
data=1,2,4,4,10
means=sorted(mean(random.choices(data,k=5))foriinrange(20))#mean是求平均
print(f'Thesamplemeanof{mean(data):.1f}hasa90%confidence'
f'intervalfrom{means[1]:.1f}to{means[-2]:.1f}')#这里的f用法
#上面程序的三次执行结果分别是:
#Thesamplemeanof4.2hasa90%confidenceintervalfrom2.4to6.6
#Thesamplemeanof4.2hasa90%confidenceintervalfrom2.6to7.2
#Thesamplemeanof4.2hasa90%confidenceintervalfrom2.0to7.0
expovariate(lambd)methodofRandominstance#随机实例的方法
Exponentialdistribution.#指数分布
lambdis1.0dividedbythedesiredmean.Itshouldbe
nonzero.(Theparameterwouldbecalled"lambda",butthatis
areservedwordinPython.)Returnedvaluesrangefrom0to
positiveinfinityiflambdispositive,andfromnegative
infinityto0iflambdisnegative.
λ(lambd)是1除以所需数的,它不能为零。(参数应当被称为lambda,但那是python保留字)
这个函数返回一个0到正无穷大的随机数(如果λ为正),或返回一个负无穷大到0的随机数,如果(如果λ为负)
gammavariate(alpha,beta)methodofRandominstance#随机实例的方法
Gammadistribution.Notthegammafunction!#伽玛分布.不是gamma函数
Conditionsontheparametersarealpha>0andbeta>0.#参数的条件是两个参数都要大于0
Theprobabilitydistributionfunctionis:#概率分布函数为:
x**(alpha-1)*math.exp(-x/beta)
pdf(x)=--------------------------------------
math.gamma(alpha)*beta**alpha
gauss(mu,sigma)methodofRandominstance#随机实例的方法
Gaussiandistribution.#高斯分布,又名正态分布或常态分布
muisthemean,andsigmaisthestandarddeviation.Thisis
slightlyfasterthanthenormalvariate()function.
Notthread-safewithoutalockaroundcalls.
#mu为期望,sigma为方差,这个函数比normalvariate()函数速度要快一点点
#没有线程调用,线程不安全。
#有两个必传参数,mu与sigma,
getrandbits(...)methodofRandominstance#随机实例的方法
getrandbits(k)->x.Generatesanintwithkrandombits.#以整型形式返回k个随机位(二进制数)。如果处理的是真正的随机事务(比如加密),这个函数尤为有用。
getstate()methodofRandominstance#随机实例的方法
Returninternalstate;canbepassedtosetstate()later.#返回捕获当前生成器内部状态的对象.该对象可以用于函数setstate()来保存当前的状态.
lognormvariate(mu,sigma)methodofRandominstance#随机实例的方法
Lognormaldistribution.
对数正态分布(logarithmicnormaldistribution)是指一个随机变量的对数服从正态分布,则该随机变量服从对数正态分布。
对数正态分布从短期来看,与正态分布非常接近。但长期来看,对数正态分布向上分布的数值更多一些。
Ifyoutakethenaturallogarithmofthisdistribution,you'llgeta
normaldistributionwithmeanmuandstandarddeviationsigma.
mucanhaveanyvalue,andsigmamustbegreaterthanzero.
#如果你对这个分布的参数取自然对数,你会得到一个均数为mu,标准差为sigma的正态分布。
#mu参数可是任何值,sigma参数必须大于0
normalvariate(mu,sigma)methodofRandominstance#随机实例的方法
Normaldistribution.#常态分布,又名正态分布和高斯分布
muisthemean,andsigmaisthestandarddeviation.#mu为期望,sigma为方差
paretovariate(alpha)methodofRandominstance#随机实例的方法
Paretodistribution.alphaistheshapeparameter.#帕累托分布;参数alpha为形状参数
#帕累托分布(Paretodistribution)是以意大利经济学家维弗雷多·帕雷托命名的,是从大量真实世界的现象中发现的幂次定律分布,
#这个分布在经济学以外,也被称为布拉德福分布。帕累托因对意大利20%的人口拥有80%的财产的观察而著名,后来被约瑟夫·朱兰和
#其他人概括为帕累托法则(80/20法则),后来进一步概括为帕累托分布的概念。
randint(a,b)methodofRandominstance#随机实例的方法
Returnrandomintegerinrange[a,b],includingbothendpoints.#返回a到b之间的一个随机整数,可取中a和b
#必须传入两个参数,且a,b都必须是整数,可以为负整数,a参数必须小于等于b参数。
random(...)methodofRandominstance#随机实例的方法
random()->xintheinterval[0,1).#无参数,生成一个0-1之间的随机数,可以是0,但不会生成1
randrange(start,stop=None,step=1,_int=)methodofRandominstance#随机实例的方法
Choosearandomitemfromrange(start,stop[,step]).#随机从一个范围中选取一个参数
Thisfixestheproblemwithrandint()whichincludesthe#这个函数修复了randint()中能取到范围右边的数字的情况
endpoint;inPythonthisisusuallynotwhatyouwant.#randint()可以取到右边范围数字的情况通常是很多人不愿意看到的
参数必须为整数,start要小于stop参数
sample(population,k)methodofRandominstance#随机实例的方法
Chooseskuniquerandomelementsfromapopulationsequenceorset.#从一个population序列或集合中取出k个随机元素
Returnsanewlistcontainingelementsfromthepopulationwhile#返还一个包含上述元素的列表,原序列或集合不会改变。
leavingtheoriginalpopulationunchanged.Theresultinglistis
inselectionordersothatallsub-sliceswillalsobevalidrandom#返还的列表是按挑选的先后顺序排列的。这样的话,所有子切片也将是合法的随机样本。
samples.Thisallowsrafflewinners(thesample)tobepartitioned#这样做允许样本中的被选中的幸运儿能按第一名第二名这样的顺序排列(在返还的列表中)
intograndprizeandsecondplacewinners(thesubslices).
Membersofthepopulationneednotbehashableorunique.Ifthe#population序列中的成员不需要是可哈希的或者是不重样的。
populationcontainsrepeats,theneachoccurrenceisapossible#如果population序列包含重复的成员,那么每次的选取都会是样本中可能的选择
selectioninthesample.
Tochooseasampleinarangeofintegers,userangeasanargument#为了在一个整数范围内选择一个样本,请使用范围值作为一个参数。
Thisisespeciallyfastandspaceefficientforsamplingfroma#当从庞大数据中取样时这样做将会非常快速并且节省内存
largepopulation:sample(range(10000000),60)#示例:sample(range(10000000),60)
seed(a=None,version=2)methodofRandominstance#随机实例的方法
Initializeinternalstatefromhashableobject.#通过可哈希对象初始化内部状态
Noneornoargumentseedsfromcurrenttimeorfromanoperating#参数为None或无参数的情况下,则seeds根据当前时间来自己选择这个值
systemspecificrandomnesssourceifavailable.#或从系统特定的随机性源中取值(如果条件可行)
If*a*isanint,allbitsareused.#如果参数a为整型,所有的bits位都将被使用
Forversion2(thedefault),allofthebitsareusedif*a*isastr,#当version参数为2(默认参数),如果参数a是一个字符串类型,bytes或bytearray,则所有的bits位都将被使用
bytes,orbytearray.Forversion1(providedforreproducingrandom#当version参数为1时(提供从老版本python中重新生成的随机序列)
sequencesfromolderversionsofPython),thealgorithmforstrand#通过对str,bytes的算法生成一个窄范围的种子。
bytesgeneratesanarrowerrangeofseeds.
setstate(state)methodofRandominstance#随机实例的方法
Restoreinternalstatefromobjectreturnedbygetstate().#保存getstate()取得并返回的对象。
shuffle(x,random=None)methodofRandominstance#随机实例的方法
Shufflelistxinplace,andreturnNone.#打乱列表x并返回Nonex为必传列表参数
Optionalargumentrandomisa0-argumentfunctionreturninga#可选参数为一个不需参数的返回0-1之间浮点数的函数
randomfloatin[0.0,1.0);ifitisthedefaultNone,the#如果可选参数为默认的None,则它会使用random.random函数方法
standardrandom.randomwillbeused.
如果你有一个更好的随机数生成器,或者说你有一个适合自己应用的随机数发生器,那么你就可以使用它而不是使用系统默认那个。
triangular(low=0.0,high=1.0,mode=None)methodofRandominstance#随机实例的方法
Triangulardistribution.#三角分布(triangulardistribution),亦称辛普森分布或三角形分布
Continuousdistributionboundedbygivenlowerandupperlimits,#三角形分布是低限为low、上限为high、众数默认为两者平均数的连续概率分布。
andhavingagivenmodevaluein-between.
http://en.wikipedia.org/wiki/Triangular_distribution
uniform(a,b)methodofRandominstance#随机实例的方法
Getarandomnumberintherange[a,b)or[a,b]dependingonrounding.#从a与b之间取一个随机数,一定可以取到a,b能否取到看b的舍入
ab两个参数必须有,可为整型可为浮点型,目前本人知道的取到b的方法的用math.ceil
这个方法返回的是一个随机数
vonmisesvariate(mu,kappa)methodofRandominstance#随机实例的方法
Circulardatadistribution.#循环数据分布或冯·米塞斯分布
muisthemeanangle,expressedinradiansbetween0and2*pi,and
kappaistheconcentrationparameter,whichmustbegreaterthanor
equaltozero.Ifkappaisequaltozero,thisdistributionreduces
toauniformrandomangleovertherange0to2*pi.
#mu是位置的度量,它的聚会在0-2*pi之间,kappa是集中度的度量,它必须大于或等于0。
#如果kappa等于0,这个分布是均匀分布,对于κ很小的情形,分布近似均匀分布,其位置度量在0-2*pi之间
weibullvariate(alpha,beta)methodofRandominstance
Weibulldistribution.#韦布尔分布
alphaisthescaleparameterandbetaistheshapeparameter.#λ>0是比例参数(scaleparameter),k>0是形状参数(shapeparameter)
#在这里alpha是比例参数,beta是形状参数
威布尔分布(Weibulldistribution),又称韦伯分布或韦布尔分布,是可靠性分析和寿命检验的理论基础。
威布尔分布:在可靠性工程中被广泛应用,尤其适用于机电类产品的磨损累计失效的分布形式。由于它可以利用概率值很容易地推断出它的分布参数,
被广泛应用于各种寿命试验的数据处理。
总结
以上就是本文关于Python3Random模块代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。