Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...