weeo
weeo

Reputation: 2799

When generating random numbers, will the same sequence being generated if the distribution function object gets created multiple times?

I know that the Pseudo random number generator should be initialized only once with one seed. However, in C++, the random number generator and distribution are separated.

Now, Should the distribution function object get created once? Or it doesn't matter? What do I mean is that does it matter to put the distribution object creation call inside or outside when generating random numbers from a distribution. Or it doesn't matter as the distribution function only maps the generator to a number.

The reason I'm asking is because I'm using the generator for generating numbers drawn from several different distributions, it would be nice to put the distribution function object creation call within each function and share the same random number generator.

int main()
{
    boost::mt19937 rng(2);

    //inside the function
    rn_int_1(rng);
    rn_int_1(rng);

    boost::mt19937 rng2(2);
    //outside the function
    boost::random::uniform_int_distribution<> six(1,6);
    rn_int_2(six,rng2);
    rn_int_2(six,rng2);
    exit(0);
}


void rn_int_1(boost::mt19937 & generator)
{
    
    boost::random::uniform_int_distribution<> six(1,6);
    cout<<six(generator)<<endl;
    cout<<six(generator)<<endl;
    cout<<six(generator)<<endl;
}
void rn_int_2(boost::random::uniform_int_distribution<> &six,boost::mt19937 & generator)
{
    cout<<six(generator)<<endl;
    cout<<six(generator)<<endl;
    cout<<six(generator)<<endl;
}

The results are:

3
2
1
6
4
6
3
2
1
6
4
6

Upvotes: 1

Views: 248

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473577

Distributions do not create sequences of random bits. That comes from the random bit engine. Distributions modify the sequence of bits in order to distribute them in some way. Put simply, the randomness comes from the engine, not the distribution.

That being said, recreating distribution objects all the time is bad form. Distributions are not stateless, and they can often retain some number of unused bits from prior invocations that would otherwise be lost if you just throw them away.

Upvotes: 2

Related Questions