randomGenerate pseudo-random numbers生成伪随机数

Source code: Lib/random.py


This module implements pseudo-random number generators for various distributions.该模块为各种分布实现伪随机数生成器。

For integers, there is uniform selection from a range. 对于整数,可以从一个范围中进行均匀选择。For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.对于序列,存在随机元素的均匀选择、生成列表的随机置换的函数以及无需替换的随机采样函数。

On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. 在实线上,有函数可以计算均匀分布、正态分布(高斯分布)、对数正态分布、负指数分布、伽马分布和贝塔分布。For generating distributions of angles, the von Mises distribution is available.为了生成角度分布,可以使用冯·米塞斯分布。

Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0). 几乎所有模块函数都依赖于基本函数random(),该函数在半开范围[0.0, 1.0)内均匀生成随机浮点。Python uses the Mersenne Twister as the core generator. Python使用Mersenne Twister作为核心生成器。It produces 53-bit precision floats and has a period of 2**19937-1. 它产生53位精度浮点,周期为2**19937-1。The underlying implementation in C is both fast and threadsafe. C中的底层实现既快速又线程安全。The Mersenne Twister is one of the most extensively tested random number generators in existence. Mersenne捻线器是现有测试最广泛的随机数生成器之一。However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.然而,由于完全确定性,它并不适用于所有目的,并且完全不适用于加密目的。

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. 该模块提供的函数实际上是random.Random类的隐藏实例的绑定方法。You can instantiate your own instances of Random to get generators that don’t share state.您可以实例化自己的Random实例,以获得不共享状态的生成器。

Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the random(), seed(), getstate(), and setstate() methods. 如果您想使用自己设计的不同基本生成器,还可以对类Random进行子类化:在这种情况下,重写Random()seed()getstate()setstate()方法。Optionally, a new generator can supply a getrandbits() method — this allows randrange() to produce selections over an arbitrarily large range.或者,新的生成器可以提供getrandbits()方法-这允许randrange()在任意大的范围内生成选择。

The random module also provides the SystemRandom class which uses the system function os.urandom() to generate random numbers from sources provided by the operating system.random模块还提供SystemRandom类,该类使用系统函数os.urandom()从操作系统提供的源生成随机数。

Warning

The pseudo-random generators of this module should not be used for security purposes. 此模块的伪随机生成器不应用于安全目的。For security or cryptographic uses, see the secrets module.有关安全或加密用途,请参阅secrets模块。

See also

M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator”, ACM Transactions on Modeling and Computer Simulation Vol. 8, No. 1, January pp.3–30 1998.M、 Matsumoto和T.Nishimura,“Mersenne捻线器:623维等分布均匀伪随机数生成器”,ACM建模与计算机模拟学报,第8卷,第1期,1998年1月,pp.3-30。

Complementary-Multiply-with-Carry recipe for a compatible alternative random number generator with a long period and comparatively simple update operations.带进位的互补乘法用于兼容的替代随机数生成器,具有长周期和相对简单的更新操作。

Bookkeeping functions记账函数

random.seed(a=None, version=2)

Initialize the random number generator.初始化随机数生成器。

If a is omitted or None, the current system time is used. 如果a省略或无,则使用当前系统时间。If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).如果随机性源由操作系统提供,则使用它们而不是系统时间(有关可用性的详细信息,请参阅os.urandom()函数)。

If a is an int, it is used directly.如果a是int,则直接使用它。

With version 2 (the default), a str, bytes, or bytearray object gets converted to an int and all of its bits are used.在版本2(默认值)中,strbytesbytearray对象转换为int,并使用其所有位。

With version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds.对于版本1(用于从较旧版本的Python中复制随机序列),strbytes的算法生成的种子范围较窄。

Changed in version 3.2:版本3.2中更改: Moved to the version 2 scheme which uses all of the bits in a string seed.移到版本2方案,该方案使用字符串种子中的所有位。

Deprecated since version 3.9: 自版本3.9以来已弃用:In the future, the seed must be one of the following types: NoneType, int, float, str, bytes, or bytearray.将来,种子必须是以下类型之一:NoneTypeintfloatstrbytesbytearray

random.getstate()

Return an object capturing the current internal state of the generator. 返回捕获生成器当前内部状态的对象。This object can be passed to setstate() to restore the state.可以将此对象传递给setstate()以恢复状态。

random.setstate(state)

state should have been obtained from a previous call to getstate(), and setstate() restores the internal state of the generator to what it was at the time getstate() was called.state应该从之前对getstate()的调用中获得,setstate()将生成器的内部状态恢复到调用getstate()时的状态。

Functions for bytes字节函数

random.randbytes(n)

Generate n random bytes.生成n个随机字节。

This method should not be used for generating security tokens. 此方法不应用于生成安全令牌。Use secrets.token_bytes() instead.请改用secrets.token_bytes()

New in version 3.9.版本3.9中新增。

Functions for integers整数函数

random.randrange(stop)
random.randrange(start, stop[, step])

Return a randomly selected element from range(start, stop, step). range(start, stop, step)中返回随机选择的元素。This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.这相当于choice(range(start, stop, step)),但实际上并不构建范围对象。

The positional argument pattern matches that of range(). 位置参数模式与range()的模式匹配。Keyword arguments should not be used because the function may use them in unexpected ways.不应使用关键字参数,因为函数可能以意外的方式使用它们。

Changed in version 3.2:版本3.2中更改: randrange() is more sophisticated about producing equally distributed values. 在生成平均分布的值方面更为复杂。Formerly it used a style like int(random()*n) which could produce slightly uneven distributions.以前,它使用int(random()*n)之类的样式,可以产生稍微不均匀的分布。

Deprecated since version 3.10: 自版本3.10以来已弃用:The automatic conversion of non-integer types to equivalent integers is deprecated. 反对将非整数类型自动转换为等效整数。Currently randrange(10.0) is losslessly converted to randrange(10). 目前,randrange(10.0)无损转换为randrange(10)In the future, this will raise a TypeError.在将来,这将引发TypeError

Deprecated since version 3.10: 自版本3.10以来已弃用:The exception raised for non-integral values such as randrange(10.5) or randrange('10') will be changed from ValueError to TypeError.对于非整数值(如randrange(10.5)randrange('10')引发的异常将从ValueError更改为TypeError

random.randint(a, b)

Return a random integer N such that a <= N <= b. 返回一个随机整数N,使a <= N <= bAlias for randrange(a, b+1).randrange(a, b+1)的别名。

random.getrandbits(k)

Returns a non-negative Python integer with k random bits. 返回具有k个随机位的非负Python整数。This method is supplied with the MersenneTwister generator and some other generators may also provide it as an optional part of the API. 此方法随MersenneTwister生成器提供,其他一些生成器也可以将其作为API的可选部分提供。When available, getrandbits() enables randrange() to handle arbitrarily large ranges.可用时,getrandbits()允许randrange()处理任意大的范围。

Changed in version 3.9:版本3.9中更改: This method now accepts zero for k.该方法现在接受k为零。

Functions for sequences序列的函数

random.choice(seq)

Return a random element from the non-empty sequence seq. 从非空序列序列seq中返回一个随机元素。If seq is empty, raises IndexError.如果seq为空,则引发IndexError

random.choices(population, weights=None, *, cum_weights=None, k=1)

Return a k sized list of elements chosen from the population with replacement. 返回从具有替换项的population中选择的k大小的元素列表。If the population is empty, raises IndexError.如果population为空,则引发IndexError

If a weights sequence is specified, selections are made according to the relative weights. 如果指定了weights序列,则根据相对权重进行选择。Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using itertools.accumulate()). 或者,如果给定cum_weights序列,则根据累积权重进行选择(可能使用itertools.accumulate()计算)。For example, the relative weights [10, 5, 30, 5] are equivalent to the cumulative weights [10, 15, 45, 50]. 例如,相对权重[10, 5, 30, 5]等同于累积权重[10, 15, 45, 50]Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.在内部,在进行选择之前,将相对权重转换为累积权重,因此提供累积权重可以节省工作。

If neither weights nor cum_weights are specified, selections are made with equal probability. 如果既没有指定weights也没有指定cum_weights,则以相同的概率进行选择。If a weights sequence is supplied, it must be the same length as the population sequence. 如果提供了权重序列,则其长度必须与population序列相同。It is a TypeError to specify both weights and cum_weights.同时指定weightscum_weights是一种TypeError

The weights or cum_weights can use any numeric type that interoperates with the float values returned by random() (that includes integers, floats, and fractions but excludes decimals). weightscum_weights可以使用与random()返回的float值互操作的任何数字类型(包括整数、浮点和分数,但不包括小数)。Weights are assumed to be non-negative and finite. 假设权重为非负且有限。A ValueError is raised if all weights are zero.如果所有权重均为零,则会产生ValueError

For a given seed, the choices() function with equal weighting typically produces a different sequence than repeated calls to choice(). 对于给定的种子,具有相同权重的choices()函数通常生成与对choice()的重复调用不同的序列。The algorithm used by choices() uses floating point arithmetic for internal consistency and speed. choices()使用的算法使用浮点算法实现内部一致性和速度。The algorithm used by choice() defaults to integer arithmetic with repeated selections to avoid small biases from round-off error.choice()使用的算法默认为整数算术,重复选择以避免舍入误差带来的小偏差。

New in version 3.6.版本3.6中新增。

Changed in version 3.9:版本3.9中更改: Raises a ValueError if all weights are zero.如果所有权重均为零,则引发ValueError

random.shuffle(x[, random])

Shuffle the sequence x in place.将序列x原地洗牌。

The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().可选参数random是一个0参数函数,返回[0.0, 1.0)中的随机浮点;默认情况下,这是函数random()

To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.要洗牌一个不可变序列并返回一个新的洗牌列表,请改用sample(x, k=len(x))

Note that even for small len(x), the total number of permutations of x can quickly grow larger than the period of most random number generators. 注意,即使对于小len(x)x的置换总数也可以快速增长,超过大多数随机数生成器的周期。This implies that most permutations of a long sequence can never be generated. 这意味着长序列的大多数置换永远不会生成。For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.例如,长度2080的序列是可以在Mersenne Twister随机数生成器的周期内拟合的最大序列。

Deprecated since version 3.9, will be removed in version 3.11: 自版本3.9以来已弃用,将在版本3.11中删除:The optional parameter random.可选参数random

random.sample(population, k, *, counts=None)

Return a k length list of unique elements chosen from the population sequence or set. 返回从总体序列或集合中选择的k长度唯一元素列表。Used for random sampling without replacement.用于随机抽样,无需更换。

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 contains repeats, then each occurrence is a possible selection in the sample.如果总体包含重复,则每个事件都是样本中可能的选择。

Repeated elements can be specified one at a time or with the optional keyword-only counts parameter. 可以一次指定一个重复元素,也可以使用可选的仅关键字counts参数。For example, sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5).例如,sample(['red', 'blue'], counts=[4, 2], k=5)等同于sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)

To choose a sample from a range of integers, use a range() object as an argument. 要从整数范围中选择样本,请使用range()对象作为参数。This is especially fast and space efficient for sampling from a large population: sample(range(10000000), k=60).这对于从大量人群中进行采样特别快速且节省空间:sample(range(10000000), k=60)

If the sample size is larger than the population size, a ValueError is raised.如果样本大小大于总体大小,则会引发ValueError

Changed in version 3.9:版本3.9中更改: Added the counts parameter.添加了counts参数。

Deprecated since version 3.9: 自版本3.9以来已弃用:In the future, the population must be a sequence. 在未来,population必须是一个序列。Instances of set are no longer supported. 不再支持set的实例。The set must first be converted to a list or tuple, preferably in a deterministic order so that the sample is reproducible.该集合必须首先转换为listtuple,最好是以确定的顺序,以便样本是可重复的。

Real-valued distributions实值分布

The following functions generate specific real-valued distributions. 以下函数生成特定的实值分布。Function parameters are named after the corresponding variables in the distribution’s equation, as used in common mathematical practice; most of these equations can be found in any statistics text.函数参数以分布方程中的相应变量命名,如常见数学实践中所用;这些方程中的大多数可以在任何统计文本中找到。

random.random()

Return the next random floating point number in the range [0.0, 1.0).返回范围[0.0, 1.0)内的下一个随机浮点数。

random.uniform(a, b)

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.返回一个随机浮点数N,使得a<=N<=b表示a <= bb <= N <= a表示b<a

The end-point value b may or may not be included in the range depending on floating-point rounding in the equation a + (b-a) * random().根据等式a + (b-a) * random()中的浮点舍入,端点值b可能包括在范围内,也可能不包括在范围内。

random.triangular(low, high, mode)

Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds. 返回一个随机浮点数N,使low<=N<=high,并且指定mode位于这些界限之间。The low and high bounds default to zero and one. lowhigh默认为0和1。The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.mode参数默认为边界之间的中点,提供对称分布。

random.betavariate(alpha, beta)

Beta distribution. β分布。Conditions on the parameters are alpha > 0 and beta > 0. 参数的条件是alpha>0beta>0Returned values range between 0 and 1.返回的值范围在0到1之间。

random.expovariate(lambd)

Exponential distribution. 指数分布。lambd is 1.0 divided by the desired mean. lambd为1.0除以所需平均值。It should be nonzero. (The parameter would be called “lambda”, but that is a reserved word in Python.) 它应该是非零的。(该参数将被称为“lambda”,但在Python中这是一个保留字。)Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.如果lambd为正,则返回值的范围为0到正无穷大;如果lambd为负,则返回值的范围为负无穷大到0。

random.gammavariate(alpha, beta)

Gamma distribution. (Not the gamma function!) 伽马分布。(不是gamma函数!)Conditions on the parameters are alpha > 0 and beta > 0.参数的条件是alpha>0beta>0

The probability distribution function is:概率分布函数为:

          x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alpha
random.gauss(mu, sigma)

Normal distribution, also called the Gaussian distribution. 正态分布,也称为高斯分布。mu is the mean, and sigma is the standard deviation. mu是平均值,sigma是标准差。This is slightly faster than the normalvariate() function defined below.这比下面定义的normalvariate()函数稍快。

Multithreading note: When two threads call this function simultaneously, it is possible that they will receive the same return value. 多线程注意:当两个线程同时调用此函数时,它们可能会收到相同的返回值。This can be avoided in three ways. 这可以通过三种方式避免。1) Have each thread use a different instance of the random number generator. 让每个线程使用不同的随机数生成器实例。2) Put locks around all calls. 在所有通话周围加锁。3) Use the slower, but thread-safe normalvariate() function instead.改用速度较慢但线程安全的normalvariate()函数。

random.lognormvariate(mu, sigma)

Log 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和标准差sigmamu can have any value, and sigma must be greater than zero.mu可以有任何值,sigma必须大于零。

random.normalvariate(mu, sigma)

Normal distribution. 正态分布。mu is the mean, and sigma is the standard deviation.mu是平均值,sigma是标准差。

random.vonmisesvariate(mu, kappa)

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. mu是平均角度,用0到2*pi之间的弧度表示,kappa是浓度参数,必须大于或等于零。If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.如果kappa等于零,则该分布在0到2*pi范围内减小为均匀随机角。

random.paretovariate(alpha)

Pareto distribution. 帕累托分布。alpha is the shape parameter.是形状参数。

random.weibullvariate(alpha, beta)

Weibull distribution. 威布尔分布。alpha is the scale parameter and beta is the shape parameter.alpha是比例参数,beta是形状参数。

Alternative Generator替代生成器

classrandom.Random([seed])

Class that implements the default pseudo-random number generator used by the random module.类,该类实现random模块使用的默认伪随机数生成器。

Deprecated since version 3.9: 自版本3.9以来已弃用:In the future, the seed must be one of the following types: NoneType, int, float, str, bytes, or bytearray.将来,seed必须是以下类型之一:NoneTypeintfloatstrbytesbytearray

classrandom.SystemRandom([seed])

Class that uses the os.urandom() function for generating random numbers from sources provided by the operating system. 类,该类使用os.urandom()函数从操作系统提供的源生成随机数。Not available on all systems. 并非在所有系统上都可用。Does not rely on software state, and sequences are not reproducible. 不依赖于软件状态,并且序列不可再现。Accordingly, the seed() method has no effect and is ignored. 因此,seed()方法没有效果,因此被忽略。The getstate() and setstate() methods raise NotImplementedError if called.getstate()setstate()方法在调用时会引发NotImplementedError

Notes on Reproducibility关于再现性的注释

Sometimes it is useful to be able to reproduce the sequences given by a pseudo-random number generator. 有时,能够再现伪随机数生成器给出的序列是有用的。By re-using a seed value, the same sequence should be reproducible from run to run as long as multiple threads are not running.通过重新使用种子值,只要多个线程没有运行,相同的序列应该可以从一个运行到另一个运行。

Most of the random module’s algorithms and seeding functions are subject to change across Python versions, but two aspects are guaranteed not to change:大多数随机模块的算法和种子函数在不同的Python版本中可能会发生变化,但有两个方面保证不会发生变化:

  • If a new seeding method is added, then a backward compatible seeder will be offered.如果添加了新的播种方法,则将提供向后兼容的播种机。

  • The generator’s random() method will continue to produce the same sequence when the compatible seeder is given the same seed.当兼容的播种机获得相同的种子时,生成器的random()方法将继续生成相同的序列。

Examples示例

Basic examples:基本示例:

>>> random()                             # Random float:  0.0 <= x < 1.0
0.37444887175646646
>>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0
3.1800146073117523

>>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange(10) # Integer from 0 to 9 inclusive
7

>>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive
26

>>> choice(['win', 'lose', 'draw']) # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split()
>>> shuffle(deck) # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement
[40, 10, 50, 30]

Simulations:模拟:

>>> # Six roulette wheel spins (weighted sampling with replacement)
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
['red', 'green', 'black', 'black', 'red', 'black']
>>> # Deal 20 cards without replacement from a deck
>>> # of 52 playing cards, and determine the proportion of cards
>>> # with a ten-value: ten, jack, queen, or king.
>>> dealt = sample(['tens', 'low cards'], counts=[16, 36], k=20)
>>> dealt.count('tens') / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial():
... return choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
...
>>> sum(trial() for i in range(10_000)) / 10_000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial():
... return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500
...
>>> sum(trial() for i in range(10_000)) / 10_000
0.7958

Example of statistical bootstrapping using resampling with replacement to estimate a confidence interval for the mean of a sample:使用替换重采样来估计样本平均值的置信区间的统计自举示例:

# http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm
from statistics import fmean as mean
from random import choices
data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95]
means = sorted(mean(choices(data, k=len(data))) for i in range(100))
print(f'The sample mean of {mean(data):.1f} has a 90% confidence '
f'interval from {means[5]:.1f} to {means[94]:.1f}')

Example of a resampling permutation test to determine the statistical significance or p-value of an observed difference between the effects of a drug versus a placebo:用于确定药物与安慰剂效应之间观察差异的统计显著性或p值重采样置换测试示例:

# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import fmean as mean
from random import shuffle
drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean(drug) - mean(placebo)

n = 10_000
count = 0
combined = drug + placebo
for i in range(n):
shuffle(combined)
new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
count += (new_diff >= observed_diff)

print(f'{n} label reshufflings produced only {count} instances with a difference')
print(f'at least as extreme as the observed difference of {observed_diff:.1f}.')
print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null')
print(f'hypothesis that there is no difference between the drug and the placebo.')

Simulation of arrival times and service deliveries for a multiserver queue:模拟多服务器队列的到达时间和服务交付:

from heapq import heapify, heapreplace
from random import expovariate, gauss
from statistics import mean, quantiles
average_arrival_interval = 5.6
average_service_time = 15.0
stdev_service_time = 3.5
num_servers = 3

waits = []
arrival_time = 0.0
servers = [0.0] * num_servers # time when each server becomes available
heapify(servers)
for i in range(1_000_000):
arrival_time += expovariate(1.0 / average_arrival_interval)
next_server_available = servers[0]
wait = max(0.0, next_server_available - arrival_time)
waits.append(wait)
service_duration = max(0.0, gauss(average_service_time, stdev_service_time))
service_completed = arrival_time + wait + service_duration
heapreplace(servers, service_completed)

print(f'Mean wait: {mean(waits):.1f} Max wait: {max(waits):.1f}')
print('Quartiles:', [round(q, 1) for q in quantiles(waits)])

See also

Statistics for Hackers a video tutorial by Jake Vanderplas on statistical analysis using just a few fundamental concepts including simulation, sampling, shuffling, and cross-validation.黑客统计Jake Vanderplas提供的关于统计分析的视频教程,仅使用几个基本概念,包括模拟、采样、洗牌和交叉验证。

Economics Simulation a simulation of a marketplace by Peter Norvig that shows effective use of many of the tools and distributions provided by this module (gauss, uniform, sample, betavariate, choice, triangular, and randrange).经济学模拟,Peter Norvig对市场的模拟,显示了该模块提供的许多工具和分布的有效使用(高斯、均匀、样本、贝塔维特、选择、三角形和随机范围)。

A Concrete Introduction to Probability (using Python) a tutorial by Peter Norvig covering the basics of probability theory, how to write simulations, and how to perform data analysis using Python.概率的具体介绍(使用Python)Peter Norvig的教程,涵盖概率论的基础知识、如何编写仿真以及如何使用Python执行数据分析。

Recipes食谱

The default random() returns multiples of 2⁻⁵³ in the range 0.0 ≤ x < 1.0. 默认的random()返回0.0 ≤ x < 1.0范围内的2⁻⁵³的倍数。All such numbers are evenly spaced and are exactly representable as Python floats. 所有这些数字都是等距的,并且可以精确地表示为Python浮点。However, many other representable floats in that interval are not possible selections. 然而,该间隔中的许多其他可表示浮点是不可能的选择。For example, 0.05954861408025609 isn’t an integer multiple of 2⁻⁵³.例如,0.05954861408025609不是2⁻⁵³的整数倍。

The following recipe takes a different approach. 以下配方采用了不同的方法。All floats in the interval are possible selections. 间隔中的所有浮动都是可能的选择。The mantissa comes from a uniform distribution of integers in the range 2⁵² ≤ mantissa < 2⁵³. 尾数来自2⁵² ≤ mantissa < 2⁵³的范围内整数的均匀分布。The exponent comes from a geometric distribution where exponents smaller than -53 occur half as often as the next larger exponent.指数来自几何分布,其中小于-53的指数出现的频率是下一个较大指数的一半。

from random import Random
from math import ldexp
class FullRandom(Random):

def random(self):
mantissa = 0x10_0000_0000_0000 | self.getrandbits(52)
exponent = -53
x = 0
while not x:
x = self.getrandbits(32)
exponent += x.bit_length() - 32
return ldexp(mantissa, exponent)

All real valued distributions in the class will use the new method:类中的所有实值分布将使用新方法:

>>> fr = FullRandom()
>>> fr.random()
0.05954861408025609
>>> fr.expovariate(0.25)
8.87925541791544

The recipe is conceptually equivalent to an algorithm that chooses from all the multiples of 2⁻¹⁰⁷⁴ in the range 0.0 ≤ x < 1.0. 该配方在概念上等同于从0.0 ≤ x < 1.0范围内的所有2⁻¹⁰⁷⁴的倍数中选择的算法。All such numbers are evenly spaced, but most have to be rounded down to the nearest representable Python float. 所有这些数字都是等距分布的,但大多数必须向下舍入到最接近的可表示Python浮点。(The value 2⁻¹⁰⁷⁴ is the smallest positive unnormalized float and is equal to math.ulp(0.0).)(值2⁻¹⁰⁷⁴是最小的正非正规浮点,等于math.ulp(0.0)。)

See also

Generating Pseudo-random Floating-Point Values a paper by Allen B. Downey describing ways to generate more fine-grained floats than normally generated by random().生成伪随机浮点值Allen B.Downey的一篇论文描述了生成比通常由random()生成的更细粒度浮点的方法。