Generating a random number in python

Reference:
Random module official document: https: //docs.python.org/3/library/random.html

random module

Principle: Mersenne Twister used as a pseudo-random number generator, which is well defined, not suitable for the field of cryptography , cryptographic module random number required secrets. At the same time, it has a cycle. ( Here I do not understand )

“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. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.”

Common Functions

  • Set Random Seed
n = 123
random.seed(n)
  • The production of a single random number
a = random.random() # [0, 1)间浮点数
a = random.uniform(2, 4.)  # [2, 4)间浮点数
a = random.randint(2, 6) # [2, 6]间整数
a = random.randrange(3, 9, 2) # start=3, end<9, step=2的等差数列中整数
a = random.normalvariate(0, 1) # 均值为0,方差为1的正态分布
a = random.gauss(0, 1) # 均值为0,方差为1的正态分布
  • sampling
b = random.choice(list("abcdea")) # 采一个样本
b = random.sample(list('aaaaaaa'), 4)  # 无放回采样多次
b = random.choices(list('a'), k=4)  # 有放回采样多次
c = list('abcdefg')
  • Sequence
random.shuffle(c) # 打乱列表元素顺序
Published 135 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/math_computer/article/details/103635647