![](/img/trans.png)
[英]How to generate a unique single random number each time in a loop in Python?
[英]Python - Generate random number from custom time
假設我在一個沒有自定義種子的系統上使用random.random()
生成了一個隨機數,但是我想也要提前生成一個隨機數,以便在那個時候使用random.random()
沒有種子的時間,它將返回相同的數字。 本質上, “預測”隨機數。 我該如何自定義隨機種子播種的時間? 我考慮根據隨機模塊的播種方式執行以下操作:
import random
import time
print random.random()
random.seed(long(time.time()*256))
print random.random()
但是,這給了我單獨的數字,我不明白為什么。 難道不應該在同一時間同時完成它們嗎?
TL;博士
我如何自定義random.seed(x)
,它將在自定義時間點播種。
假設random.random()
每次都被稱為new,因此它是生成的第一個數字,而不是第二,第三,第四等。
請注意,我不想在過去執行此操作,因此不要獲取狀態然后將其還原,但是能夠生成將來將要生成的內容。
澄清:將使用的系統未實施urandom。
其實我錯了。
可以這樣做:方法如下:
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
我想到你居然做有urandom
各種各樣的或至少是以下不拋出異常
from binascii import hexlify as _hexlify
from os import urandom as _urandom
a = long(_hexlify(_urandom(16)), 16)
可以?
現在假設讓我們修改可以在這里找到的隨機庫。
首先替換
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()
結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.