Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do std::random_device and std::mt19937 follow an uniform distribution?

I'm trying to convert this line of matlab in C++: rp = randperm(p);

Following the randperm documentation:

randperm uses the same random number generator as rand

And in rand page:

rand returns a single uniformly distributed random number

So rand follows an uniform distribution. My C++ code is based on:

std::random_device rd;
std::mt19937 g(rd());
std::shuffle(... , ... ,g);

My question is: the code above follows an uniform distribution? If not, how to do so?

like image 611
justHelloWorld Avatar asked Dec 11 '22 16:12

justHelloWorld


1 Answers

The different classes from the C++ random number library roughly work as follows:

  • std::random_device is a uniformly-distributed random number generator that may access a hardware device in your system, or something like /dev/random on Linux. It is usually just used to seed a pseudo-random generator, since the underlying device wil usually run out of entropy quickly.
  • std::mt19937 is a fast pseudo-random number generator using the Mersenne Twister engine which, according to the original authors' paper title, is also uniform. This generates fully random 32-bit or 64-bit unsigned integers. Since std::random_device is only used to seed this generator, it does not have to be uniform itself (e.g., you often seed the generator using a current time stamp, which is definitely not uniformly distributed).
  • Typically, you use a generator such as std::mt19937 to feed a particular distribution, e.g. a std::uniform_int_distribution or std::normal_distribution which then take the desired distribution shape.
  • std::shuffle, according to the documentation,

    Reorders the elements in the given range [first, last) such that each possible permutation of those elements has equal probability of appearance.

In your code example, you use the std::mt19937 PRNG to feed std::shuffle. So, std::mt19937 is uniform, and std::shuffle should also behave uniformly. So, everything is as uniform as it can be.

like image 151
mindriot Avatar answered Feb 06 '23 03:02

mindriot