hackingcpp / comments

Comments regarding hackingcpp.com
0 stars 0 forks source link

cpp/recipe/random_number_generator #3

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Combine C++ Random Engine With Distribution | hacking C++

How to make a single random number generator object from a standard library random distribution and a random engine. Two solutions are presented: one using a mutable lambda and one using a custom function class.

https://hackingcpp.com/cpp/recipe/random_number_generator.html

savek-cc commented 3 years ago

Please, please, please do not forget to properly seed the RNG. The above example always uses the same static, pre-defined seed value - meaning you will get the same sequence of "random" every time you run your program. As of why this is a bad idea, check https://www.theregister.com/2021/07/06/kaspersky_password_manager/ for example. https://wiki.sei.cmu.edu/confluence/display/cplusplus/MSC51-CPP.+Ensure+your+random+number+generator+is+properly+seeded gives more details about the topic - an can be used as a reference. https://diego.assencio.com/?index=6890b8c50169ef45b74db135063c227c also has a complete example on the topic. In short: Use std::random_device device; std::mt19937 generator(device()); to properly initialize the rng.

hackingcpp commented 3 years ago

Oops - you are absolutely right that I forgot the seed here; that should be part of the examples; a stupid oversight, especially considering that I have a separate article about seeding;

Of course there are numerous applications where you actually want the same reproducible pseudo-random sequence every time you run a program. Debugging MCMC simulations for example. But one should always add an option to control the seed of course.

BTW, note that random_device is just an LCG on many platforms, so doesn't give you a "true" source of entropy and therefore is essentially equivalent to not using it at all.