Boost logo

Boost Users :

Subject: Re: [Boost-users] [Random] Passing an arbitrary uniform random number generator to a function
From: Joseph Wakeling (joseph.wakeling_at_[hidden])
Date: 2010-05-08 12:46:12


On 04/28/2010 10:45 AM, Joseph Gauterin wrote:
> You're not missing anything - a lot of boost/std/std::tr1 is designed
> to be used with templates rather than runtime polymorphism - mixing
> the two isn't trivial.

I had a long and careful think about this, and my program design, and
which of the two approaches might actually be more appropriate.

It turns out that, contra my assumptions, a template approach works well
-- it means some changes in the design/philosophy of the classes I'm
building, but I think on balance they are positive changes.

I tried the type erasure method and ran into two problems with it. The
first was that the underlying random number generator isn't itself
updated when runtime_generator is called, despite the use of references.
 If you do,

    mt19937 rng;
    runtime_generator<uint32_t> rng1(rng);
    for(int i=0;i!=10;++i)
        cout << uniform_real<double> (0.0,1.0) (rng1) << " ";
    cout << endl;

    runtime_generator<uint32_t> rng2(rng);
    for(int i=0;i!=10;++i)
        cout << uniform_real<double> (0.0,1.0) (rng2) << " ";
    cout << endl;

... you'll get the same sequence of 10 numbers.

The second factor is that type erasure seems dodgy when not all the
random number generators have the same return_type, and this can cause
problems. For example, if you replace the mt19937 in the code above
with a lagged_fibonacci607, it will just generate a series of zeros,
because the lagged_fibonacci's return type is a double in [0,1).

The "obvious" thing to do is just to use runtime_generator<double> but
that has its own problems, because then e.g. the uniform_int
distribution won't work with it.

In summary, the risk of making buggered code seems quite high, so it
seems the better option to either use the Boost random number generators
with templated code, or to use an alternative that supports runtime
polymorphism naturally, like GSL.

Thanks once again for all the advice and assistance. It was very
informative and I learned quite a bit from following up on the
suggestions provided.

Final question -- what is the appropriate way to save the state of a
Boost random number generator so that another one can be seeded to take
exactly the same state?

Best wishes,

    -- Joe


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net