跳到正文

科技·工程

基于Python的真随机数生成器

Forever_Rain约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年2月23日
更新
2026年5月16日
篇幅
约 2 分钟

版本

  1. v1当前

常用的 random.randint 是基于固定算法1 生成的伪随机数,于是做了一个真随机。

Python
def random_(a=None, b=None):
    try:
        import os
        import struct
    except:
        pass
    if a is None and b is None:
        randbyte=os.urandom(7)
        randint_=int.from_bytes(randbyte,byteorder='big')
        seed=randint_>>(56-53)
        return seed/(1<<53)
    if a is not None and b is None:
        return os.urandom(a)
    if a is not None and b is not None:
        size_=b-a+1
        nbits=size_.bit_length()
        nbyte=(nbits+7)//8
        while True:
            randbyte=os.urandom(nbyte)
            randint_=int.from_bytes(randbyte,byteorder='big')
            if randint_<size_:
                return a+randint_

脚注

  1. Mersenne Twister(MT19937),梅森旋转算法MT19937变体。 回到正文↩

原文