Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++11 - random device usage

Tags:

random

c++11

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.

like image 654
jean Avatar asked Mar 06 '14 13:03

jean


People also ask

What is a random device?

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.

What is #include random in C++?

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.

How do you generate a random number between 1 and 10 in C++?

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++.

What is mt19937?

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.


1 Answers

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.

like image 156
PureW Avatar answered Oct 06 '22 08:10

PureW