使用 random.seed(seed) 重现过去的模拟,但由于值不同而出现问题

Reproduce past simulation using random.seed(seed) but having issues as values turn out to differ

我正在尝试重现我之前 运行 的模拟,以便我在文本文件中记录当前日期时间的种子,然后使用记录的日期时间种子来获得相同的我之前得到的值

但是,我不确定为什么得出的值与我在之前的模拟中 运行 的值不相似。

这是我尝试 运行 程序时得到的结果:

=================== RESTART: /Users/ivanteong/Desktop/e.py ===================
Choose 1 to run simulation based on random seed of current time, or choose 2 to reproduce past simulation: 1
2017-05-20 18:55:51
0.902032491409618
0.33535058732344564
>>> 
=================== RESTART: /Users/ivanteong/Desktop/e.py ===================
Choose 1 to run simulation based on random seed of current time, or choose 2 to reproduce past simulation: 2
Enter the seed of current time recorded: 2017-05-20-18-55-51
2017-05-20 18:55:51
0.759062526352241
0.058976331409061576
>>> 

代码如下。

import math
import random
from datetime import datetime

# reproducibility
reproduce = int(input("Choose 1 to run simulation based on random seed of current time, or choose 2 to reproduce past simulation: "))
if reproduce == 1:
    # seeding random based on current time and writing into text file for reproducibility  
    string_seed = datetime.strftime(datetime.now(), '%Y-%m-%d-%H-%M-%S')
    f = open('seed.txt', 'a')
    f.write(str(string_seed))
    f.write('\n')
    f.close()
    seed = datetime.strptime(string_seed, '%Y-%m-%d-%H-%M-%S')
    print(seed)
elif reproduce == 2:
    stored_seed = str(input("Enter the seed of current time recorded: "))
    seed = datetime.strptime(stored_seed, '%Y-%m-%d-%H-%M-%S')
    print(seed)

def randExponential(rateLambda):
    random.seed(seed)
    print(random.random())
    return -math.log(1.0 - random.random()) / rateLambda

print(randExponential(5))

当我尝试在控制台中仅使用数字对此进行测试时,似乎没问题,所以不确定为什么我在使用日期时间库时遇到问题。

>>> random.seed(3)
>>> random.random()
0.23796462709189137
>>> random.seed(3)
>>> random.random()
0.23796462709189137
>>> 

你的变量 seed 不是全局变量,所以当你在 randExponential 函数中使用 random.seed(seed) 时,它会传递一个尚未初始化的种子变量,所以它只是通过 None ,这是默认值,而是使用当前时间。只需在调用 randExponential 之前调用 random.seed(seed) 并摆脱函数中的调用,它应该可以工作,或者您可以将种子传递给函数

编辑:

出于某种原因,我一直没能找到,[​​=17=] 函数似乎在每次调用时都会稍微更改字符串,从而创建不同的随机生成,而删除这些使其有效

这是我的代码:

import math
import random
from datetime import datetime


reproduce = int(input("Choose 1 to run simulation based on random seed of current time, or choose 2 to reproduce past simulation: "))
if reproduce == 1:
    seed = datetime.strftime(datetime.now(), '%Y-%m-%d-%H-%M-%S')
    print(seed)
    f = open('seed.txt', 'a')
    f.write(str(seed))
    f.write('\n')
    f.close()

elif reproduce == 2:
    seed = str(input("Enter the seed of current time recorded :"))
    print(seed)

def randExponential(rateLambda, seed):
    random.seed(seed)
    print(random.random())
    return -math.log(1.0 - random.random()) / rateLambda