Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

Python3 Random模块代码详解

来源:中文源码网    浏览:212 次    日期:2024-04-23 21:32:55
【下载文档:  Python3 Random模块代码详解.txt 】


Python3 Random模块代码详解
描述
random() 方法返回随机生成的一个实数,它在[0,1)范围内。
import random
help(random)
FUNCTIONS
betavariate(alpha, beta) method of Random instance # 随机实例的方法
Beta distribution. # β分布
Conditions on the parameters are alpha > 0 and beta > 0. # 必须传入大于0的alpha 与beta参数
Returned values range between 0 and 1. # 返回一个0 -1 之间的值,这个值你是随机的!
a = random.betavariate(999999, 99999999999999999) # 第一次执行结果:9.995974671839104e-12 第二次执行结果:1.0006927848540756e-11
贝塔分布(Beta Distribution) 是一个作为伯努利分布和二项式分布的共轭先验分布的密度函数,在机器学习和数理统计学中有重要应用。
在概率论中,贝塔分布,也称Β分布,是指一组定义在(0,1) 区间的连续概率分布。
choice(seq) method of Random instance
Choose a random element from a non-empty sequence. # 随机从一个不为空的序列中取出一个元素,参数必须不为空
Python包含 6 种内建的序列,包括列表、元组、字符串、Unicode字符串、buffer对象和xrange对象。
choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance # 随机实例的方法
Return a k sized list of population elements chosen with replacement. # 通过chosen with replacement(就是每次抽取的机会都是相同的或按权重来的,前面的选择不会影响后面选择的概率)的方式获取一个由k个元素组成的随机列表
If the relative weights or cumulative weights are not specified, # 如果未指定相对权重或累积权重,
the selections are made with equal probability. # 则选择的概率相等。
从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() for i in range(10000)) / 10000)
trial2 = lambda : 2500 <= sorted(random.choices(range(10000), k=5))[2] < 7500
print(sum(trial2() for i in range(10000)) / 10000 )
from statistics import mean
data = 1, 2, 4, 4, 10
means = sorted(mean(random.choices(data, k=5)) for i in range(20)) # mean是求平均
print(f'The sample mean of {mean(data):.1f} has a 90% confidence '
f'interval from {means[1]:.1f} to {means[-2]:.1f}') # 这里的f用法
# 上面程序的三次执行结果分别是:
# The sample mean of 4.2 has a 90% confidence interval from 2.4 to 6.6
# The sample mean of 4.2 has a 90% confidence interval from 2.6 to 7.2
# The sample mean of 4.2 has a 90% confidence interval from 2.0 to 7.0
expovariate(lambd) method of Random instance # 随机实例的方法
Exponential distribution. # 指数分布
lambd is 1.0 divided by the desired mean. It should be
nonzero. (The parameter would be called "lambda", but that is
a reserved word in Python.) Returned values range from 0 to
positive infinity if lambd is positive, and from negative
infinity to 0 if lambd is negative.
λ(lambd)是1除以所需数的,它不能为零。(参数应当被称为lambda,但那是python保留字)
这个函数返回一个0到正无穷大的随机数(如果 λ 为正),或返回一个负无穷大到0的随机数,如果(如果 λ 为负)
gammavariate(alpha, beta) method of Random instance # 随机实例的方法
Gamma distribution. Not the gamma function! # 伽玛分布.不是gamma函数
Conditions on the parameters are alpha > 0 and beta > 0. # 参数的条件是两个参数都要大于0
The probability distribution function is: # 概率分布函数为:
x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alpha
gauss(mu, sigma) method of Random instance # 随机实例的方法
Gaussian distribution. # 高斯分布,又名正态分布或常态分布
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls.
# mu为期望,sigma为方差,这个函数比normalvariate()函数速度要快一点点
# 没有线程调用,线程不安全。
# 有两个必传参数,mu与sigma,
getrandbits(...) method of Random instance # 随机实例的方法
getrandbits(k) -> x. Generates an int with k random bits. # 以整型形式返回k个随机位(二进制数)。如果处理的是真正的随机事务(比如加密),这个函数尤为有用。
getstate() method of Random instance # 随机实例的方法
Return internal state; can be passed to setstate() later. # 返回捕获当前生成器内部状态的对象.该对象可以用于函数setstate()来保存当前的状态.
lognormvariate(mu, sigma) method of Random instance # 随机实例的方法
Log normal distribution.
对数正态分布(logarithmic normal distribution)是指一个随机变量的对数服从正态分布,则该随机变量服从对数正态分布。
对数正态分布从短期来看,与正态分布非常接近。但长期来看,对数正态分布向上分布的数值更多一些。
If you take the natural logarithm of this distribution, you'll get a
normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.
# 如果你对这个分布的参数取自然对数,你会得到一个均数为mu,标准差为sigma的正态分布。
# mu参数可是任何值,sigma参数必须大于0
normalvariate(mu, sigma) method of Random instance # 随机实例的方法
Normal distribution. # 常态分布,又名正态分布和高斯分布
mu is the mean, and sigma is the standard deviation. # mu为期望,sigma为方差
paretovariate(alpha) method of Random instance # 随机实例的方法
Pareto distribution. alpha is the shape parameter. # 帕累托分布;参数alpha为形状参数
# 帕累托分布(Pareto distribution)是以意大利经济学家维弗雷多・帕雷托命名的, 是从大量真实世界的现象中发现的幂次定律分布,
# 这个分布在经济学以外,也被称为布拉德福分布。帕累托因对意大利20%的人口拥有80%的财产的观察而著名,后来被约瑟夫・朱兰和
# 其他人概括为帕累托法则(80/20法则),后来进一步概括为帕累托分布的概念。
randint(a, b) method of Random instance # 随机实例的方法
Return random integer in range [a, b], including both end points. # 返回a到b之间的一个随机整数,可取中a和b
# 必须传入两个参数,且a, b都必须是整数,可以为负整数,a参数必须小于等于b参数。
random(...) method of Random instance # 随机实例的方法
random() -> x in the interval [0, 1). # 无参数,生成一个0-1之间的随机数,可以是0,但不会生成1
randrange(start, stop=None, step=1, _int=) method of Random instance # 随机实例的方法
Choose a random item from range(start, stop[, step]). # 随机从一个范围中选取一个参数
This fixes the problem with randint() which includes the # 这个函数修复了randint()中能取到范围右边的数字的情况
endpoint; in Python this is usually not what you want. # randint()可以取到右边范围数字的情况通常是很多人不愿意看到的
参数必须为整数,start要小于stop参数
sample(population, k) method of Random instance # 随机实例的方法
Chooses k unique random elements from a population sequence or set. # 从一个population序列或集合中取出k个随机元素
Returns a new list containing elements from the population while # 返还一个包含上述元素的列表,原序列或集合不会改变。
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random # 返还的列表是按挑选的先后顺序排列的。这样的话,所有子切片也将是合法的随机样本。
samples. This allows raffle winners (the sample) to be partitioned # 这样做允许样本中的被选中的幸运儿能按第一名第二名这样的顺序排列(在返还的列表中)
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the # population序列中的成员不需要是可哈希的或者是不重样的。
population contains repeats, then each occurrence is a possible # 如果population序列包含重复的成员,那么每次的选取都会是样本中可能的选择
selection in the sample.
To choose a sample in a range of integers, use range as an argument # 为了在一个整数范围内选择一个样本,请使用范围值作为一个参数。
This is especially fast and space efficient for sampling from a # 当从庞大数据中取样时这样做将会非常快速并且节省内存
large population: sample(range(10000000), 60) # 示例:sample(range(10000000), 60)
seed(a=None, version=2) method of Random instance # 随机实例的方法
Initialize internal state from hashable object. # 通过可哈希对象初始化内部状态
None or no argument seeds from current time or from an operating # 参数为None或无参数的情况下,则seeds根据当前时间来自己选择这个值
system specific randomness source if available. # 或从系统特定的随机性源中取值(如果条件可行)
If *a* is an int, all bits are used. # 如果参数a为整型,所有的bits位都将被使用
For version 2 (the default), all of the bits are used if *a* is a str, # 当version参数为2(默认参数),如果参数a是一个字符串类型,bytes或bytearray,则所有的bits位都将被使用
bytes, or bytearray. For version 1 (provided for reproducing random # 当version参数为1时(提供从老版本python中重新生成的随机序列)
sequences from older versions of Python), the algorithm for str and # 通过对str,bytes的算法生成一个窄范围的种子。
bytes generates a narrower range of seeds.
setstate(state) method of Random instance # 随机实例的方法
Restore internal state from object returned by getstate(). # 保存getstate()取得并返回的对象。
shuffle(x, random=None) method of Random instance # 随机实例的方法
Shuffle list x in place, and return None. # 打乱列表x并返回None x为必传列表参数
Optional argument random is a 0-argument function returning a # 可选参数为一个不需参数的返回0-1之间浮点数的函数
random float in [0.0, 1.0); if it is the default None, the # 如果可选参数为默认的None,则它会使用random.random函数方法
standard random.random will be used.
如果你有一个更好的随机数生成器,或者说你有一个适合自己应用的随机数发生器,那么你就可以使用它而不是使用系统默认那个。
triangular(low=0.0, high=1.0, mode=None) method of Random instance # 随机实例的方法
Triangular distribution. # 三角分布(triangular distribution),亦称辛普森分布或三角形分布
Continuous distribution bounded by given lower and upper limits, # 三角形分布是低限为low、上限为high、众数默认为两者平均数的连续概率分布。
and having a given mode value in-between.
http://en.wikipedia.org/wiki/Triangular_distribution
uniform(a, b) method of Random instance # 随机实例的方法
Get a random number in the range [a, b) or [a, b] depending on rounding. # 从a与b之间取一个随机数,一定可以取到a,b能否取到看b的舍入
a b两个参数必须有,可为整型可为浮点型,目前本人知道的取到b的方法的用math.ceil
这个方法返回的是一个随机数
vonmisesvariate(mu, kappa) method of Random instance # 随机实例的方法
Circular data distribution. # 循环数据分布或冯・米塞斯分布
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.
# mu 是位置的度量,它的聚会在0-2*pi之间,kappa是集中度的度量,它必须大于或等于0。
# 如果kappa等于0,这个分布是均匀分布,对于κ很小的情形,分布近似均匀分布,其位置度量在0-2*pi之间
weibullvariate(alpha, beta) method of Random instance
Weibull distribution. # 韦布尔分布
alpha is the scale parameter and beta is the shape parameter. # λ>0是比例参数(scale parameter),k>0是形状参数(shape parameter)
# 在这里alpha是比例参数,beta是形状参数
威布尔分布(Weibull distribution),又称韦伯分布或韦布尔分布,是可靠性分析和寿命检验的理论基础。
威布尔分布:在可靠性工程中被广泛应用,尤其适用于机电类产品的磨损累计失效的分布形式。由于它可以利用概率值很容易地推断出它的分布参数,
被广泛应用于各种寿命试验的数据处理。
总结
以上就是本文关于Python3 Random模块代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关内容