Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Random Number Generator State in C++11

I would like to be able to save the state of a random number generator in a .txt file and read it back in. I have heard that with c++11, this can be done using the << and >> operators. However, I'm not sure how exactly I would do this. I have a random number generator initialized as follows:

mt19937 myRandomGenerator(1);
normal_distribution<double> myDistribution(0.0, 1.0);

I would like to be able to save the state of myRandomGenerator in the file save.txt. How would I do thi?

like image 615
covertbob Avatar asked Aug 21 '13 15:08

covertbob


1 Answers

It's just as described, write it using operator<< and read the state back in using operator>>.

#include <fstream>
#include <random>
#include <cassert>

int main() {
  std::mt19937 myRandomGenerator(1);

  {
    std::ofstream fout("save.txt");
    fout << myRandomGenerator;
  }

  std::ifstream fin("save.txt");
  std::mt19937 myRandomGeneratorCopy;
  fin >> myRandomGeneratorCopy;
  assert(myRandomGenerator == myRandomGeneratorCopy);
}
like image 150
bames53 Avatar answered Sep 27 '22 21:09

bames53