简体   繁体   English

python 3:random.seed():在哪里调用它?

[英]python 3: random.seed(): where to call it?

I need to make sure all the randomness in my program is fully replicable. 我需要确保程序中的所有随机性都是完全可复制的。 Where should I place a call to random.seed()? 我应该在哪里拨打random.seed()?

I thought it should be in my main.py module, but it imports other modules that happen to use random functions. 我认为它应该在我的main.py模块中,但是它导入了碰巧使用随机函数的其他模块。

I can carefully navigate through my imports to see which one is the first to execute, but the moment I change my code structure I will have to remember to redo this analysis again. 我可以仔细浏览我的导入,看看哪一个是第一个执行,但是当我改变我的代码结构时,我将不得不记得再次重做这个分析。

Is there any simple and safe solution? 有没有简单安全的解决方案?

It is actually safe to execute code in the "import section" of your main module, so if you are unsure about importing other modules that might or might not use the random module, maybe bypassing your seed, you can of course use something like 在主模块的“导入部分”中执行代码实际上是安全的,因此如果您不确定导入可能使用或不使用随机模块的其他模块,可能绕过您的种子,您当然可以使用类似的东西

import random
random.seed(seed_value)

import something
import else

if __name__ == "__main__":
    main()

If you want random to be replicable, it's probably best to make an instance of random.Random in your application, call seed() on that instance, and use that instance for your random numbers. 如果你想随机可复制,最好在应用程序中random.Random实例,在该实例上调用seed() ,并将该实例用于随机数。

random.random() actually uses a singleton of the random.Random class, for convenience for people who don't care enough to make their own class instance. random.random()实际上使用random.Random类的单例,以方便那些不在乎自己创建类实例的人。 But that singleton is potentially shared with other modules that might want to call random.random() to generate random numbers for whatever reason. 但是,该单例可能与其他可能想要调用random.random()以生成随机数的模块共享。 That's why in your case you're better off instantiating your own random.Random instance. 这就是为什么在你的情况下你最好实例化你自己的random.Random实例。

Quoting from the docs : 引用文档

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. 该模块提供的函数实际上是random.Random类的隐藏实例的绑定方法。 You can instantiate your own instances of Random to get generators that don't share state. 您可以实例化您自己的Random实例,以获取不共享状态的生成器。

You could roll your own singleton that encapsulates random. 你可以滚动自己封装随机的单例。 You can then use Python documentation on random getstate and setstate to change the state of the random number generator. 然后,您可以在随机 getstate和setstate 使用Python文档来更改随机数生成器的状态。 That would give your program two random number generators essentially. 这将为您的程序提供两个随机数生成器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM