Setting the initial acceleration :: random

I would like to use reset random sequences using different numbers of seeds. 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 am doing something very bad. How can I solve this problem?

+8
c ++ boost random seed
source share
4 answers

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

Many thanks!

+14
source share

After calling the gener.seed () function, you should call normal.reset (). This is indicated to ensure that the normal output will not depend on any previous output from the generator.

(The distribution probably caches some kind of state that needs to be cleared.)

+5
source share

I believe boost::variate_generator<> makes a copy of your boost::mt19937 gener . Therefore, when you copy your copy of gener , it does not affect the rng object that has already been built. Building a new rng object with each re-order should give you the behavior you want (disclaimer: not verified!)

+1
source share

Itโ€™s great that the problem is solved! But I think I just realized why Alanโ€™s method doesnโ€™t work ...

When writing boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > rng(gener, normal) you did not create another copy of gener because it is a link call, but you created another copy of normal using variate_generate .

So, instead of normal.reset , which only resets the original normal , you should use rng.distribution().reset() . But you can just save gener.seed() , which I suspect will have the same effect as rng.engine().seed() .

I tested it in my code and it worked as expected.

Well, just in case, someone doesnโ€™t care :)

+1
source share

Source: https://habr.com/ru/post/651426/


All Articles