Can I choose between different Boost pseudo random number generators at runtime?

I use the Boost Random library to generate random numbers for Monte Carlo simulation. To test my results, I would like to be able to use different RNG engines for different starts. Ideally, I would like to use a command-line option to determine which RNG to use at runtime, rather than, for example, selecting RNG at compile time via typedef.

Is there a base class T such that the following is possible: or, if not, the obvious reason why not?

#include <boost/random.hpp> int main() { unsigned char rng_choice = 0; T* rng_ptr; // base_class pointer can point to any RNG from boost::random switch(rng_choice) { case 0: rng_ptr = new boost::random::mt19937; break; case 1: rng_ptr = new boost::random::lagged_fibonacci607; break; } boost::random::uniform_int_distribution<> dice_roll(1,6); // Generate a variate from dice_roll using the engine defined by rng_ptr: dice_roll(*rng_ptr); delete rng_ptr; return 0; } 
+4
source share
2 answers

Just use Boost.Function to erase the type.

Edit: A simple example.

 #include <iostream> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/random/mersenne_twister.hpp> int main() { boost::random::mt19937 gen; boost::random::uniform_int_distribution<> dist(1, 6); boost::function<int()> f; f=boost::bind(dist,gen); std::cout << f() << std::endl; return 0; } 
+5
source

Looking at the source code for mersenne twister, for example, there is no base class. It seems you will have to implement the class hierarchy you need.

+2
source

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


All Articles