存储随机状态 [英] Storing a Random state

查看:39
本文介绍了存储随机状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个程序:

  1. 包括随机性
  2. 可以在某些点停止执行并保存其状态(以 XML 格式)
  3. 可以从保存的状态开始执行
  4. 是确定性的(因此程序可以从同一状态运行两次并产生相同的结果)

这里的问题是保存随机性.我可以在开始时初始化它,但从一个状态到另一个状态,我可能会生成 0 到 1000 个随机数.

The problem here is saving the randomness. I can initialize it at start, but from state to state I may generate anywhere from 0 to 1000 random numbers.

因此,我可以看到 3 个选项:

Therefore, I have 3 options I can see:

  1. 存储种子,以及随机生成数字的次数,然后在加载状态时,多次运行随机数生成器.
  2. 状态保存时,将种子增加 N
  3. 状态保存时,随机生成下一个种子

选项 1 的问题是运行时间,而且非常不可行.

The problem with option 1 is the run time, and is pretty infeasible.

但是,我不确定 2 或 3 是否会产生良好的随机结果.如果我运行两个随机生成器,一个以 X 为种子,另一个以 X+1 为种子,它们的结果会有多大不同?如果第一个以 X 为种子,第二个以 X.random() 为种子怎么办?

However, I'm unsure whether 2 or 3 will produce good random results. If I run two random generators, one seeded with X, the other seeded with X+1, how different will their results be? What if the first is seeded with X, and the second is seeded with X.random()?

以防万一,我使用的是 Python 3.

In case it makes a difference, I'm using Python 3.

推荐答案

您可以使用 random.getstate() 保存 PRNG 的状态(然后,例如,使用 pickle 将其保存到磁盘.稍后,random.setstate(state) 会将您的 PRNG 返回到它所处的状态.

You can save the state of the PRNG using random.getstate() (then, e.g., use pickle to save it to disk. Later, a random.setstate(state) will return your PRNG to exactly the state it was in.

这篇关于存储随机状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆