4

Per如何生成可重复的随机数序列?可以设置 random 模块的状态,以便您可以期望随后对 randint 的调用返回相同的数字。

我看到这种方法的一个限制是状态是在模块级别设置的(本质上是一个全局变量),因此似乎不可能创建多个可重复的随机数流/迭代器(但流的调用可以任意交错) ) 与当前机制。是否有任何解决方法/替代库可以实现这一点?

4

2 回答 2

8

它不必在模块级别维护状态 - 请参阅模块的random文档

该模块提供的函数实际上是random.Random类的隐藏实例的绑定方法。您可以实例化您自己的 Random 实例以获取不共享状态的生成器。这对于多线程程序特别有用,为每个线程创建不同的 Random 实例,并使用该jumpahead()方法使每个线程看到的生成序列可能不重叠。

于 2013-08-14T14:45:08.860 回答
5

random.Random() is what you're looking for.

http://hg.python.org/cpython/file/2.7/Lib/random.py#l72

All the random.* module-level functions are simply proxies of a shared Random() instance that lives at random._inst.

http://hg.python.org/cpython/file/2.7/Lib/random.py#l879

For your situation, all you'd do is instantiate N random.Random() instances; they will have independent internal RNG states and can be seeded/consumed without affecting one another.

In fact, I consider it a best practice to create your own Random() instances for non-trivial applications, specifically so it can be easily made repeatable if there's a state-dependent bug, etc. Particularly in test suites, this can be invaluable.

于 2013-08-14T14:45:26.023 回答