vendredi 18 décembre 2015

Boost random numbers inside a class as static member

I am running a simulation of 'Foo' objects. Each Foo must have a random 'type' t. I want to encapsulate the random number generation into the class by (static) member functions:

#include <boost/random.hpp>

class Foo {
public:
    static void set_seed(int seed);
    Foo();
    void print() { std::cout << t << std::endl; };
private:
    double t;
    static boost::mt19937 rng;
    static boost::uniform_01<> unif;
    static boost::variate_generator<boost::mt19937, boost::uniform_01<> > type;
};

Foo::Foo() {
    // create a new friend with random parameters
    double t = type();
};

void Foo::set_seed(int seed) {
    rng = boost::mt19937(seed);
}

boost::mt19937 Foo::rng; //reserve storage
// boost::uniform_01<> Foo::unif = boost::uniform_01<>(); // apparently not necessary
boost::variate_generator<boost::mt19937, boost::uniform_01<> > Foo::type(rng, unif); // initialize

int main() {
    Foo::set_seed(1);
    Foo f;
    f.print();
    Foo g;
    g.print();
    return 0;
}

The code compiles (by g++ -I/usr/include/boost148/ test.cpp on RHEL 6.7) but the results do not look anything like uniform(0,1) randoms. (something like 6.95301e-310 and 0 instead.)

Can anyone tell me:

  1. Is this a reasonable approach for MC simulations? I have to create a large quantities of Foos in parallel, but parallelization is done at a higher level (in R) where each MPI worker will load the corresponding compiled code (both on shared and non-share memory cpus). I think static members are 'mpi-parallel-safe' in this sense but tell me if I am wrong.
  2. How can I get the random number initialization right?

I would also stay clear from C++11 as the code has to run on a cluster with less-than-most-recent software.




Aucun commentaire:

Enregistrer un commentaire