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.
The /dev/random device is intended to provide high quality, cryptographically secure random output and will only return output for which sufficient (an equal or greater amount) random input is available to generate the output.
rand() rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.
rand() function generates random number and when you use rand()%10 , it will give you last digit of the number. Since we require random number between 1 and 10, we have used rand()%10+1 to generate random number between 1 and 10 in C++.
std::mt19937(since C++11) class is a very efficient pseudo-random number generator and is defined in a random header file. It produces 32-bit pseudo-random numbers using the well-known and popular algorithm named Mersenne twister algorithm.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With