提升variate_generator - 编写和恢复其状态

时间:2012-11-06 14:42:49

标签: boost random state

我遇到了关于随机数生成器状态的问题。具体而言,一旦恢复保存的引擎状态,就会生成略微关闭的随机数序列。在所有情况下,恢复的序列似乎已向上或向下移动一个。例如:

1. Create bivariate generator with an MT19937 engine and a standard uniform distribution.
2. Generate some random normal variables.
3. Save the state of the engine. I'll call it state 1.
4. Generate and keep track of the next 5 random normal variables.
5. Repeat steps 2 to 4 to obtain a state 2 and then a state 3.

观察结果(仅供说明):

State 1
Actual  Restored state (appears to have shifted up)
a       b
b       c
c       d
d       e
e       f

State 2
Actual  Restored state (appears to have shifted down)
j       i
k       j
l       k
m       l
n       m

State 3
Actual  Restored state (appears to have shifted up again)
r       s
s       t
t       u
u       v
v       w

代码:

boost::mt19937 engine(seed);
boost::normal_distribution<double> dd(0, 1);
boost::variate_generator<boost::mt19937&, boost::normal_distribution<double>> rr(engine, dd);
std::stringstream ss1; std::stringstream ss2; std::stringstream ss3;

for (long p=0; p<20; p++) {rr();} 
ss1 << engine;
for (long p=0; p<5; p++) {
  std::cout << rr() << "\n"; // keep track of these
}

// repeat for states 2 and 3, i.e., ss2 and ss3

ss1 >> engine; 
for (long p=0; p<5; p++) {
  std::cout << rr() << "\n"; // compare with the above numbers
} 

// repeat for states 2 and 3

My Boost版本是1.47.0,我在VS2010中为64位Windows编译代码。非常感谢任何建议尝试重新调整&#34;这些被保存的州。谢谢!

1 个答案:

答案 0 :(得分:0)

正在发生的事情是normal_distribution实例在发送器调用之间保持自己的一些状态,此外还由引擎本身保存。该发行版具有专门用于清除它的reset方法。来自Boost docs

  

效果:分发的后续使用不依赖于值   在调用重置之前由任何引擎生成。

在保存或加载引擎状态之前立即调用rr.distribution().reset()将确保在重新加载时获得相同的结果。