pseudo-random number generators for various distributions.
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).
Python uses the Mersenne Twister as the core generator.
The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets
module.
The functions supplied by this module are actually bound methods of a hidden instance of the random.Random
class.
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.
seed: 当设置相同的seed时,可以得到相同的随机数。
1 random.seed(1) 2 a2 = random.random() 3 print(a2) 4 5 random.seed(0) 6 a11 = random.random() 7 print(a11 == a1) 8 9 result: 10 0.8444218515250481 11 0.13436424411240122 12 True
getstate:
Return an object capturing the current internal state of the generator. This object can be passed to setstate()
to restore the state.
从下面的结果来看,可能和seed有关。
1 s1 = random.getstate() # a tuple of length 3 2 print(len(s1[1]), s1) 3 random.seed(0) 4 a1 = random.random() 5 s2 = random.getstate() 6 print(len(s2[1]), s2) 7 8 random.seed(1) 9 a2 = random.random() 10 s3 = random.getstate() 11 print(len(s3[1]), s3) 12 13 random.seed(0) 14 a11 = random.random() 15 s4 = random.getstate() 16 print(len(s4[1]), s4) 17 print(s4 == s2) 18 19 result: 20 625 (3, (2147483648, ..., 3028008404, 624), None) 21 625 (3, (1372342863, ..., 418789356, 2), None) 22 625 (3, (2145931878, ..., 3656373148, 2), None) 23 625 (3, (1372342863, ..., 418789356, 2), None) 24 True
setstate: 貌似功能与seed一样,都是到达某一状态。
1 random.seed(0) 2 s1 = random.getstate() 3 a1 = random.random() 4 s2 = random.getstate() 5 print(a1, s2 == s1) # s2 != s1, 因为生成了一次随机数,状态变了 6 7 random.seed(1) 8 a2 = random.random() 9 s3 = random.getstate() 10 print(s3 == s2) # False 11 12 # random.seed(0) 13 random.setstate(s1) # 设置为s1才能使a11 == a1, 和s2状态不同。有点像翻书的过程,翻到那一页,首先看到的内容总是一样的。 14 s4 = random.getstate() 15 print(s4 == s1) # True 16 a11 = random.random() 17 s5 = random.getstate() 18 print(a11 == a1, s5 == s2) # True True 在s4 == s1的状态下,执行一个相同操作,执行后的状态也相同。
getrandbits:
Returns a Python integer with k random bits. This method is supplied with the MersenneTwister generator and some other generators may also provide it as an optional part of the API. When available, getrandbits()
enables randrange()
to handle arbitrarily large ranges.
k random bits
is supplied with
1 k = random.getrandbits(1) # 0、1 2 k = random.getrandbits(2) # 0、1、2、3 3 k = random.getrandbits(3) # 0、1、2、3、4、5、6、7 4 print(k)
Functions for integers
randrange:
This is equivalent to choice(range(start, stop, step))
.
Keyword arguments should not be used because the function may use them in unexpected ways.
randrange()
is more sophisticated about producing equally distributed values. 【Formerly it used a style like int(random()*n)
which could produce slightly uneven distributions.】
1 r = random.randrange(2, 5) 2 c = random.choice(range(2, 5)) 3 print(c)
randint(a, b):
Return a random integer N such that a <= N <= b
. Alias for randrange(a, b+1)
.
Functions for sequences
choice(seq):
arg is a seq.
If seq is empty, raises IndexError
.
choices(population, weights=None, *, cum_weights=None, k=1):
Return a k sized list of elements chosen from the population with replacement(复位,即可以放回重复抽取). If the population is empty, raises IndexError
.
If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using itertools.accumulate()
). For example, the relative weights [10, 5, 30, 5]
are equivalent to the cumulative weights [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(从这点看来,前面的权重指的是某数值被选中的概率). If a weights sequence is supplied, it must be the same length as the population sequence. It is a TypeError
to specify both weights and cum_weights.
1 cs = random.choices([1, 3, 5, 7, 9], weights=[8, 6, 4, 2, 5], k=2) 2 print(cs) # with replacement, [3, 3]
shuffle(x[, random]):
Shuffle the sequence.
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()
.
To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x))
instead.
1 l = [1, 3, 5, 7, 9, 3] 2 s = random.shuffle(l) # 修改序列本身,所以参数必须是可变类型。 3 print(l, s)
sample(population, k):
Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged.
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.
To choose a sample from a range of integers, use a range()
object as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), k=60)
.
If the sample size is larger than the population size, a ValueError
is raised.
1 # l = (1, 3, 5, 7, 9, 3) 2 l = [1, 3, 5, 7, 9, 3] #可变类型也可 3 s = random.sample(l, 2) 4 print(l, s) # (1, 3, 5, 7, 9, 3) [9, 1]
Real-valued distributions
random(): Return the next random floating point number in the range [0.0, 1.0).
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
.
1 equation: 2 return a + (b-a) * self.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. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.
gauss(mu, sigma):
Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate()
function.