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

2024-10-02 18:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我找不到一个好办法来做这个。我有档案全局.py有了这个:

import random

myRandom=None


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

那么从一个主要的方面来说:

^{pr2}$

然后在主调用的模块中,我会:

from globals import myRandom

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


Tags: 模块文件项目pyimportnonedefrandom
2条回答

我将使用一个文件来避免global,并将数据和逻辑稍微分开。在

种子_处理程序.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())

模拟1.py

^{pr2}$

模拟2.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. 只需提示用户输入yes/no来覆盖 现有价值。在
  1. 正如@jDo在评论中提到的,将globals.py重命名为randGlobal.py

  2. 添加了一个用于测试的模块testResult.py


在随机全局.py在

import random

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

在测试结果.py在

^{pr2}$

在主.py在

import randGlobal

# Add a module for testing
import testResult


def test():
    result = testResult.randOutput()
    print result


# main
if __name__ == "__main__":

    seed=10
    randGlobal.initSeed(seed)
    # after init, hava a test
    test()

相关问题 更多 >