Martijn 的回答非常简洁地回顾了 Python 可以访问的随机数生成器。
如果您想查看生成的伪随机数据的属性,请random.zip
从http://www.fourmilab.ch/random/下载,然后在大量随机数据样本上运行它。特别是 χ²(卡方)检验对随机性非常敏感。对于真正随机的序列,来自 χ² 检验的百分比应该在 10% 到 90% 之间。
对于一个游戏,我猜 Python 内部使用的 Mersenne Twister 应该是足够随机的(除非你正在建立一个在线赌场:-)。
如果您想要纯随机性,并且您使用的是 Linux,则可以从/dev/random
. 这只会从内核的熵池(从中断到达的不可预测的时间收集)中产生随机数据,因此如果您用尽它,它将阻塞。此熵用于初始化(种子)由/dev/urandom
. 在 FreeBSD 上,提供数据的 PRNG/dev/random
使用 Yarrow 算法,该算法通常被认为是加密安全的。
编辑:我对来自random.randint
. 首先创建一百万个随机字节:
import random
ba = bytearray([random.randint(0,255) for n in xrange(1000000)])
with open('randint.dat', 'w+') as f:
f.write(ba)
然后我运行Fourmilabent
的程序:
Entropy = 7.999840 bits per byte.
Optimum compression would reduce the size
of this 1000000 byte file by 0 percent.
Chi square distribution for 1000000 samples is 221.87, and randomly
would exceed this value 93.40 percent of the times.
Arithmetic mean value of data bytes is 127.5136 (127.5 = random).
Monte Carlo value for Pi is 3.139644559 (error 0.06 percent).
Serial correlation coefficient is -0.000931 (totally uncorrelated = 0.0).
现在对于 χ² 检验,距离 50% 越远,数据越可疑。如果一个非常挑剔,值 <10% 或 >90% 被认为是不可接受的。约翰沃克,作者ent
称这个值“几乎是可疑的”。
作为对比,这里是我之前运行的来自 FreeBSD 的 Yarrow prng 的 10 MiB 的相同分析:
Entropy = 7.999982 bits per byte.
Optimum compression would reduce the size
of this 10485760 byte file by 0 percent.
Chi square distribution for 10485760 samples is 259.03, and randomly
would exceed this value 41.80 percent of the times.
Arithmetic mean value of data bytes is 127.5116 (127.5 = random).
Monte Carlo value for Pi is 3.139877754 (error 0.05 percent).
Serial correlation coefficient is -0.000296 (totally uncorrelated = 0.0).
虽然其他数据似乎没有太大差异,但 χ² 百分比更接近 50%。