Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有一种很好的方法可以在模块之间共享random的种子(在python中)?_Python_Random_Seed_Globals - Fatal编程技术网

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

有没有一种很好的方法可以在模块之间共享random的种子(在python中)?,python,random,seed,globals,Python,Random,Seed,Globals,我有一个具有不同主文件的项目(用于不同的模拟)。 当我运行一个主文件时,它应该将种子设置为random(和numpy.random),项目中的所有模块都应该使用该种子 我找不到一个好办法。我有一个文件globals.py,其中包含: import random myRandom=None def initSeed(seed): global myRandom myRandom =random.Random(seed) 然后,我从一个主要的角度: if __name__ =

我有一个具有不同主文件的项目(用于不同的模拟)。 当我运行一个主文件时,它应该将种子设置为random(和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)
...
然后在主调用的模块中,我执行以下操作:

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

  • 正如@jDo在评论中提到的,将
    globals.py
    重命名为
    randGlobal.py

  • 为测试添加了模块
    testResult.py


  • randGlobal.py testResult.py main.py
    我会使用一个文件来避免
    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())
    
    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()
    
    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()
    
    模拟1.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())
    
    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()
    
    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()
    
    模拟2.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())
    
    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()
    
    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会覆盖存储的种子值;这可能不可取。可以添加以下功能之一:

  • 另存为json并加载到字典;那样没什么 将被覆盖,每个种子值都可以有注释、时间戳和 与之关联的用户生成的标签
  • 只需提示用户“是/否”即可覆盖 现有价值

  • 如果要使用
    global
    ,则应在所有使用该变量的函数中声明该变量
    global
    。您可以使用类和子类,但也可以将值写入文件。我想您应该在当前设置中通过
    globals.myRandom
    访问变量
    myRandom
    。顺便说一句,
    globals
    已在Python中定义,因此请将文件名更改为其他文件名(而不是
    glob
    -也可以)
    它应该设置一个随机种子,项目中的所有模块都应该使用该种子。
    听起来像是在寻找单例?我只是想知道你的用例场景是什么我的用例是研究:我有模型,我必须以不同的方式运行它们(例如,使用不同的参数,绘制不同的东西,等等)。我为模型和模拟文件创建模块,就像执行概要文件一样。在我看来,这是一个特别好的主意,因为OP提到他们这样做是为了研究目的。他们可能应该以比全局变量更持久的方式存储种子,以防需要复制运行或扩展模型。@Paul谢谢,我认为你是对的。实际上,在这种情况下,覆盖值的整个想法可能是不明智的。必须对随机模块进行反向工程,以找出在给定输出中创建了哪个种子值,这种想法肯定是不吸引人的!