Python - 从自定义时间生成随机数

时间:2014-12-04 00:18:06

标签: python python-2.7 random

所以说我在一个没有自定义种子的系统上使用random.random()生成一个随机数,但是说我想提前生成一个随机数,这样如果我使用{{1}那时没有播种就会返回相同的数字。实质上,“预测”随机数。我如何定制随机用于种子自身的时间?我想根据随机模块种子的方式做以下几点:

random.random()

然而,这给了我单独的数字,我不明白为什么。它们是否应该在同一时间完成?

TL;博士

如何自定义import random import time print random.random() random.seed(long(time.time()*256)) print random.random() 在自定义时间点播种的位置。

假设random.seed(x)每次被称为a-new,因此它是第一个生成的数字,而不是第二个,第三个,第四个等。

请注意,我不想在过去执行此操作,因此请不要获取状态然后将其还原,但能够生成将来生成的内容。

澄清:将使用的系统没有urandom实现。

2 个答案:

答案 0 :(得分:0)

其实我错了。

可以这样做: 方法如下:

import time
import random

def predicite_future(delay):
    random.seed(long(time.time() + delay) * 256)
    return random.random()

delay = 10

print "The next value will be:",predicite_future(delay)
print "Waiting for %s seconds"%delay
time.sleep(delay)
random.seed(long(time.time()) * 256)
print "As predicited, the value is:",random.random()

输出:

The next value will be: 0.359211550742
Waiting for 10 seconds
As predicited, the value is: 0.359211550742

答案 1 :(得分:0)

我认为你确实有urandom种类,或者至少以下会抛出异常

from binascii import hexlify as _hexlify
from os import urandom as _urandom
a = long(_hexlify(_urandom(16)), 16)
是吗?

现在假设允许修改可以找到的随机库here

首先替换

    if a is None:
        try:
            a = long(_hexlify(_urandom(16)), 16)
        except NotImplementedError:
            import time
            a = long(time.time() * 256) # use fractional seconds

只是

    if a is None:
        import time
        a = long(time.time() * 256) # use fractional seconds
        print ("bottom - the seed is", a) # debug

现在在if __name__ == "__main__"文件的底部删除测试,然后输入

if __name__ == '__main__':
    from time import time
    then1 = long(time() * 256)
    from random import random, seed
    then2 = long(time() * 256)
    assert then1 == then2 # if fails here the time has changed

    print random() # unseeded
    seed(then1)
    print random() # use the seed with think it uses

现在假设我们想要预测的时间是d,那么我们可以then1 = long((time()+d) * 256)预测未来random.random()的结果。