Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::mt19937 and rng state save/load & portability

I want to be able to save and load the state of an RNG so I can reproduce the same random values from a given point (application save/snapshot).

I see there is an operator << and >> overload, which seems to save to a string as a sequence of numbers.

  • Is that the best/only way to save? I wouldn't mind just having the fixed-size binary state value not this space separated string thing that I then need to prefix or put delimiters around for my file format.
  • Is this at all portable? e.g. can I transfer this between different compiler versions, or even between MSVC and GCC to produce the same data set given identically configured distributions (to a small margin of error in the case of floating point, and exact for integer maths)?
like image 816
Fire Lancer Avatar asked Dec 31 '14 22:12

Fire Lancer


1 Answers

Yes, operator<< and operator>> are the only way to import or export a random number generator's state. You can easily convert the textual representation to and from binary, if you'd like.

De-serializing and serializing mt19937 state should be portable between implementations. The result of reading and writing the engine's state via the streaming operators is well defined by the standard, as long as you ensure the streams are imbued with the same locale.

See § 26.5.1.5 for the requirements of operator<< and operator>>, followed by § 26.5.3.2 for the textual representation of mersenne_twister_engine, which mt19937 is a well defined typedef of.

like image 146
Collin Dauphinee Avatar answered Oct 14 '22 22:10

Collin Dauphinee