S_Thwaite
S_Thwaite

Reputation: 43

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

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;
}

Upvotes: 4

Views: 376

Answers (2)

Jan Herrmann
Jan Herrmann

Reputation: 2767

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;
}

Upvotes: 5

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

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.

Upvotes: 2

Related Questions