常用的 random.randint 是基于固定算法1 生成的伪随机数,于是做了一个真随机。
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_脚注
Mersenne Twister(MT19937),梅森旋转算法MT19937变体。 回到正文↩