mercredi 2 décembre 2015

c++ std::normal_distribution gives inconsistent random numbers when restoring from file

I'm writing a Monte Carlo simulation and implemented checkpointing. I want to obtain the exact same results, whether or not I restart the simulation from a checkpoint or continue beyond it. However, I encountered some weird behavior with std::normal_distribution:

I am using a std::mt19937 rng; as the RNG and seed it to a fixed number. I draw a certain amount of random numbers via both std::uniform_real_distribution uniform; and std::normal_distribution normal;. Then, I write the state of the rng to an ofstream os:

os << rng << endl;
os << <some other stuff>...

Immediately afterwards, I draw a couple more numbers:

os << uniform(rng) << endl;
os << uniform(rng) << endl;
os << uniform(rng) << endl;
os << normal(rng) << endl;
os << normal(rng) << endl;
os << normal(rng) << endl;
os << uniform(rng) << endl;
os << uniform(rng) << endl;
os << uniform(rng) << endl;

I get the following output:

0.727133
0.215537
0.516879
-2.12532
0.314652
1.78136
0.511111
0.83119
0.637067

If I however restart from the checkpoint, i.e. initializing the generator from an ifstream is:

is >> rng;
is >> <some other stuff>...

and drawing the same 9 random numbers (3 uniform, 3 normal, 3 uniform), I get:

0.727133
0.215537
0.516879
0.314652
1.78136
1.28201
0.637067
0.298175
0.802607

You see, that the uniform numbers are identical until a normal number is drawn after with the states of the rng differs. Stepping through with gdb confirmed that.

Any idea? Is this a bug in my standard library implementation? I'm using g++ with -O0.




Aucun commentaire:

Enregistrer un commentaire