bolov bolov - 3 months ago 13
C++ Question

Why not just use random_device?

I am a bit confused about the c++11 random library.

What I understand: we need two separate concepts:


  • random engine (which can be pseudo (need seed) or real)

  • distribution: it maps the numbers obtained from the engine to a specific interval, using a specific distribution.



What I don't understand is why not just use this:

std::random_device rd;
std::uniform_int_distribution<int> dist(1, 5);

// get random numbers with:
dist(rd);


As far as I can tell this works well.

Instead, this is what I found on most examples/sites/articles:

std::random_device rd;
std::mt19937 e{rd()}; // or std::default_random_engine e{rd()};
std::uniform_int_distribution<int> dist{1, 5};

// get random numbers with:
dist(e);


I am not talking about special use, e.g. cryptography, just your basic getting started articles.

My suspicion is because
std::mt19937
(or
std::default_random_engine
) accepts a seed, it can be easier to debug by providing the same seed during a debug session.

Also, why not just:

std::mt19937 e{std::random_device{}()};

Answer

This article is a good point to start.

I'm going to synthesize just few points:

  • It Has Unknown Cost.

    How costly it is to read a number from this “device”? That is unspecified. It could, for example, be reading from /dev/random on a Linux system, which can block for an extended period waiting for entropy (which is itself problematic for a variety of reasons).

For my personal experience I've notified that std::random_device is usually slower than a simple Pseudo-randomic algorithm. That could be no true in general, but usually it does. That because it may involve physical devices, or other hardware than the simple CPU.

  • It Might Actually Be Deterministic .

    C++11's std::random_device is not required to be nondeterministic! Implementations can and do implement it as a simple RNG with a fixed seed, so it produces the same output for every run of the program.

Comments