Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting seed boost::random

I would like to reset random sequences by using different seed numbers. When running this test code:

boost::mt19937 gener(1);
boost::normal_distribution<> normal(0,1);
boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > rng(gener, normal);
cout << rng() << endl;
cout << rng() << endl;
cout << rng() << endl;
gener.seed(2);
cout << rng() << endl;
cout << rng() << endl;
gener.seed(1);
cout << rng() << endl;
gener.seed(2);
cout << rng() << endl;
gener.seed(3);
cout << rng() << endl;

I get the following output:

# seed(1) via constructor
-2.971829031
1.706951063
-0.430498971
# seed(2)
-2.282022417
-0.5887503675
# seed(1)
0.2504171986
# seed(2)
-0.5887503675
# seed(3)
0.2504171986

Obviously I'm doing something very wrong. How may I overcome this problem?

like image 249
anton skvorts Avatar asked Jan 24 '11 04:01

anton skvorts


People also ask

How do I fix a random seed in Matlab?

Set and Restore Generator SettingsSet the random number generator to the default seed ( 0 ) and algorithm (Mersenne Twister), then save the generator settings. Create a 1-by-5 row vector of random values between 0 and 1. Change the generator seed and algorithm, and create a new random row vector.

How do you keep the same random number in Python?

Reproducible Coding with the seed() Function The seed() function is used to save the state of the random() function, allowing it to generate the same random number(s) on multiple executions of the code on the same or different machines for a specific seed value.


2 Answers

Following Jim, Alan and Igor suggestions made some changes to the code: rng.engine().seed() instead of gener.seed(), and called rng.distribution().reset() after the call to rng.engine().seed() and it worked like a charm.

Many thanks!

like image 66
anton skvorts Avatar answered Nov 15 '22 19:11

anton skvorts


You should call normal.reset() after the call to gener.seed(). That is specified to ensure that the output of normal will not depend on any previous output from gener.

(The distribution is probably caching some state that you need to clear out.)

like image 33
Alan Stokes Avatar answered Nov 15 '22 21:11

Alan Stokes