jean
jean

Reputation: 2990

c++11 - random device usage

What is the different between

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dist(0, 100);
for (int n = 0; n < 100; ++n)
    std::cout<<dist(gen)<<std::endl; 

and

std::random_device rd;
std::uniform_int_distribution<int> dist(0, 100);
for (int n = 0; n < 100; ++n)
    std::cout<<dist(rd)<<std::endl; 

The first example use rd() as a seed, but the output is similar, I want know what's the advantage of first.

Upvotes: 11

Views: 4128

Answers (1)

PureW
PureW

Reputation: 5085

The difference is that in the first example you specifically set the mersenne-twister as the random-number generator. The mersenne-twister is a pseudo-random generator and is seeded with a value from std::random_device. The mersenne-twister is considered a really good pseudo-random generator and will produce large volumes of high quality pseudo-random values quickly.

The std::random_device is a "true" random-number generator in that it uses different stochastic processes to generate numbers that in practice are random. As such, I believe it isn't suitable if you need lots of random numbers very fast because it depends on these stochastic events happening (think user input, the noise in ad-measurements etc) for it to create a random state.

Upvotes: 9

Related Questions