参考:
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) # 打乱列表元素顺序
本文深入探讨了Python中random模块的使用方法,包括基于Mersenne Twister算法的伪随机数生成原理及其在非密码学领域的应用。文章详细介绍了如何通过设置随机种子、生成不同类型的随机数(如浮点数、整数、正态分布数),以及进行随机采样和列表排序等操作。
485

被折叠的 条评论
为什么被折叠?



