Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to select between different Boost pseudo-random number generators at run-time?

Tags:

c++

random

boost

I'm using the Boost Random library to generate random numbers for a Monte Carlo simulation. In order to check my results, I'd like to be able to use different RNG engines for different runs. Ideally I'd like to use a command-line option to determine which RNG to use at run-time, instead of e.g. selecting the RNG at compile-time through a typedef.

Is there a base class T such that something like the following is possible; or if not, an 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;
}
like image 892
S_Thwaite Avatar asked Mar 23 '23 21:03

S_Thwaite


2 Answers

Simply use Boost.Function for type erasure.

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;
}
like image 159
Jan Herrmann Avatar answered Mar 30 '23 01:03

Jan Herrmann


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

like image 45
Ivaylo Strandjev Avatar answered Mar 29 '23 23:03

Ivaylo Strandjev