Boost logo

Boost :

From: Anders Edin (anders.edin_at_[hidden])
Date: 2004-07-08 10:44:24


// The following program illustrates a problem in Boost.Random.

// Is this the desired behavior?

// If so, what is the reason for this?

// I use Boost version 1.31 and GCC version 3.3.3 on Suse 9.1

#include <vector>
#include <algorithm>
#include <boost/random.hpp>

// Definition of the random number generator
typedef boost::mt19937 engine_t;
typedef boost::uniform_int<int> distribution_t;
typedef boost::variate_generator<engine_t, distribution_t> rng_t;

int main()
{
    const unsigned int N = 13, A = 0, B = 1000;
    std::vector<int> run1(N), run2(N), run3(N);

// Generate some random integers
    {
        engine_t engine;
        distribution_t distribution(A,B);
        rng_t rng(engine, distribution);
        std::generate(run1.begin(), run1.end(), rng);
    }

// Verify that I get the same sequence if I start again
    {
        engine_t engine;
        distribution_t distribution(A,B);
        rng_t rng(engine, distribution);
        std::generate(run2.begin(), run2.end(), rng);
    }

// It appears that the generator restarts for each generate, since
// the generate algorithm creates a copy of the functor so that
// its state is lost
    {
        engine_t engine;
        distribution_t distribution(A,B);
        rng_t rng(engine, distribution);
        std::generate(run3.begin(), run3.begin()+N/2, rng);
        std::generate(run3.begin()+N/2, run3.end(), rng);
    }

// For me it would seem more natural if the engine class would be a
// singleton, so that there can be only one object of any particular
// random generator engine type.

// Our purpose for using random numbers is to simulate physical processes.
// I can't think of a case when there would be a need for several random
// engines, even if there can of course be many different random
// distributions in an application.

// Having the same random number sequence in different parts of a simulation
// can probably create very strange behaviour, since the numbers from the
// different engines of the same type will be perfectly correlated.

// Perhaps other applications have use of several random engines?

    for(unsigned i=0; i<N; ++i) {
        if(i==N/2)
            std::cout<<"Halfway there!"<<std::endl;
        std::cout
            <<run1[i]
            <<" == "<<run2[i]
            <<" == "<<run3[i]
            <<std::endl;
    }
    
    return 0;
}

// Anders Edin
// Sidec Technologies AB


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk