mercredi 22 juin 2016

c++ Boost random ints from multiple ranges using single generator

Using boost::random I'm trying to sample sets of uniformly distributed integers from different ranges, but using the same underlying random number generator. For each range I am defining a different function returning the the random numbers. However, it seems that each function returns the same number.

An example illustrating the approach:

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/random.hpp>

struct RandomNumberGenerator {
  boost::mt19937 generator;

  RandomNumberGenerator(long seed) {
    generator.seed(seed);
  }

  boost::function<int()> getRandomFunctionInt(int min, int max) {
    boost::uniform_int<> uni_dist(min, max);
    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > uni(generator, uni_dist);

    boost::function<int()> f;
    f = boost::bind(uni_dist, generator);
    return f;
  }
};

int main (int argc, char* argv[]) {
  RandomNumberGenerator rng(1729);
  boost::function<int()> runif1 = rng.getRandomFunctionInt(0,  1000);
  boost::function<int()> runif2 = rng.getRandomFunctionInt(0, 10000);

  for (int i=0; i<10; ++i) {
    std::cout << runif1() << ", " << runif2() << std::endl;
  }
}

The output was:

212, 2121
623, 6226
259, 2590
[...]

Is there any way to un-correlate the functions? For the sake of reproducibility of my experiment I would like to work with a single seed.




Aucun commentaire:

Enregistrer un commentaire