gpt4 book ai didi

python - 有没有一种在模块之间共享随机种子的好方法(在 python 中)?

转载 作者:太空狗 更新时间:2023-10-29 21:49:11 25 4
gpt4 key购买 nike

我有一个包含不同主文件的项目(用于不同的模拟)。当我运行其中一个主文件时,它应该将种子设置为随机(和 numpy.random),并且项目中的所有模块都应该使用该种子。

我找不到执行此操作的好方法。我有一个 globals.py 文件:

import random

myRandom=None


def initSeed(seed):
global myRandom
myRandom =random.Random(seed)

然后从一个主要的我做:

if __name__ == "__main__":

seed=10
globals.initSeed(seed)
...

然后在 main 调用的模块中,我做:

from globals import myRandom

但是 myRandom 在模块中的值为 None(即使我在 main 中修改了它!)。为什么,以及如何解决它?有更好的方法吗?

最佳答案

我会使用一个文件来避免 global 并稍微分离数据和逻辑。

seed_handler.py

# file that stores the shared seed value 
seed_val_file = "seed_val.txt"

def save_seed(val, filename=seed_val_file):
""" saves val. Called once in simulation1.py """
with open(filename, "wb") as f:
f.write(str(val))

def load_seed(filename=seed_val_file):
""" loads val. Called by all scripts that need the shared seed value """
with open(filename, "rb") as f:
# change datatype accordingly (numpy.random.random() returns a float)
return int(f.read())

simulation1.py

import random
import seed_handler

def sim1():
""" creates a new seed and prints a deterministic "random" number """
new_seed = int("DEADBEEF",16) # Replace with numpy.random.random() or whatever
print "New seed:", new_seed
# do the actual seeding of the pseudo-random number generator
random.seed(new_seed)
# the result
print "Random: ", random.random()
# save the seed value so other scripts can use it
seed_handler.save_seed(new_seed)

if __name__ == "__main__":
sim1()

simulation2.py

import random
import seed_handler

def sim2():
""" loads the old seed and prints a deterministic "random" number """
old_seed = seed_handler.load_seed()
print "Old seed:", old_seed
# do the actual seeding of the pseudo-random number generator
random.seed(old_seed)
# the result
print "Random: ", random.random()

if __name__ == "__main__":
sim2()

输出:

user@box:~/$ python simulation1.py 
New seed: 3735928559
Random: 0.0191336454935

user@box:~/$ python simulation2.py
Old seed: 3735928559
Random: 0.0191336454935

附录

我刚刚在评论中看到这是为了研究。此时,执行 simulation1.py 会覆盖存储的种子值;这可能是不可取的。可以添加以下功能之一:

  1. 保存为json并加载到字典;那样没什么会被覆盖,每个种子值都可以有注释、时间戳和用户生成的与之关联的标签。
  2. 简单地提示用户是/否以覆盖现有值(value)。

关于python - 有没有一种在模块之间共享随机种子的好方法(在 python 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36304187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com