python中的随机数生成

参考:
random模块官方文档:https://docs.python.org/3/library/random.html

random模块

原理:使用Mersenne Twister作为伪随机数生成器,它是完全确定的,不适合于密码领域,密码中随机数需要使用模块secrets。同时,它有周期。(这里不太理解

“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.”

常用函数

  • 设置随机种子
n = 123
random.seed(n)
  • 生产单个随机数
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的正态分布
  • 采样
b = random.choice(list("abcdea")) # 采一个样本
b = random.sample(list('aaaaaaa'), 4)  # 无放回采样多次
b = random.choices(list('a'), k=4)  # 有放回采样多次
c = list('abcdefg')
  • 排序
random.shuffle(c) # 打乱列表元素顺序
发布了135 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/math_computer/article/details/103635647