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) # 打乱列表元素顺序
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值