Natalia
Natalia

Reputation: 564

Re-initializing random distribution

Is it reasonable to expect that a distribution from <random> re-initialized before each next number request behaves the same way as if it was initialized once? In other words, does this:

std::default_random_engine generator;
int p[10]={};
for (int i=0; i<nrolls; ++i) {
 std::uniform_int_distribution<int> distribution(0,9);
 int number = distribution(generator);
 ++p[number];
} 

have the same distribution as that

std::uniform_int_distribution<int> distribution(0,9);
std::default_random_engine generator;
int p[10]={};
for (int i=0; i<nrolls; ++i) {
 int number = distribution(generator);
 ++p[number];
} 

I've checked that for uniform and normal distribution it empirically holds true. Can I expect it from every distribution in <random>?

Upvotes: 2

Views: 263

Answers (1)

Casey
Casey

Reputation: 10936

I essentially do what your first implementation does. Construct one every time I need a distribution.

That said, yes, the behavior of the different distributions are guaranteed by the standard to behave in specific ways.

STL recommends, that since distributions are relatively cheap, don't worry about constructing one every time you need one or need a new range. He also says if you don't want to construct one every time, you can use the param member function to change the distribution range.

Microsoft Channel9 link if the above direct Youtube link dies (seek to 30 minutes in): https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

EDIT

I was re-watching a CppCon talk from a few years ago that discusses this exact question. The result? Constructing distributions as local variables even inside loops is 4.5 times faster.

Upvotes: 2

Related Questions