开发者

How to Save State of C++0X Random Number Generator

I'm playing around with the new C++0X random library and based on this question:

What is the standard way to get the state of a C++0x random number generator?

it seems that if you don't know the seed for the current state of a random generator, the only way to save its state is by storing the generator in a stream. To do this I wrote the following

#include <iostream>
#include <sstream>
#include <random>

int main(int /*argc*/, char** /*argv*/)
{
  std::mt19937 engine1;
  unsigned int var = engine1(); // Just to get engine1 out of its initial state
  std::stringstream input;
  input << engine1;
  std::mt19937 engine2;
  input >> engine2;
  std::cout<<"Engine comparison: "<<(engine1 == engine2)<<std::endl;
  std::cout<<"Engine 1 random number "<<engine1()<<std::endl;
  std::cout<<"Engine 2 random number "<<engine2()<<std::endl;
}

This outputs

Engine comparison: 1

Engine 1 random number 581869302

Engine 2 random number 4178893912

I have开发者_C百科 a few questions:

  • Why are the next numbers from engine1 and engine2 different?
  • Why are the two engines comparing equal even though their next numbers are different?
  • What am I doing wrong in my example and what is the correct way to save the state of a random engine to get repeatability in later runs (assuming you don't know the seed to set the desired state)?

Thank you.


This looks like a bug to me. I ran your code on libc++ and the output is:

Engine comparison: 1
Engine 1 random number 581869302
Engine 2 random number 581869302
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜