5

Suppose I have this cross-platform program

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::cout << "rd.entropy = " << rd.entropy() << std::endl;
    std::uniform_int_distribution<int> dist(0, 9);

    for (int i = 0; i < 10; ++i) {
        std::cout << dist(rd) << " ";
    }
    std::cout << std::endl;
}

On Linux Mint 17.1 with g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 it always produces random numbers:

$ g++ -std=c++11 testrd.cpp -o testrd
$ ./testrd
rd.entropy = 0
9 2 6 0 8 1 0 2 3 8 
$ ./testrd
rd.entropy = 0
3 6 2 4 1 1 8 3 7 5 
$ ./testrd
rd.entropy = 0
3 4 4 6 8 5 4 6 6 3 
$ ./testrd
rd.entropy = 0
2 4 7 7 6 3 0 1 1 9 
$ ./testrd
rd.entropy = 0
7 2 5 0 7 8 6 6 0 6 

But how can I be sure, that on any system std::random_device is random? For example, on Windows with mingw-gcc it is not random (see, for example this question), it will produce same sequence on start. But on MSVC++ (according to S. Lavavej) starting from 2013.4 it is random.

I thought that I can do this:

if (rd.entropy() != 0) {
    // initialize some generator like mt19937 with rd()
}
else {
    // use another seed generator (for example, time in milliseconds)
}

i.e. comparing rd.entropy() with 0. But it turns out to be wrong.

How can I test std::random_device for randomness?

Community
  • 1
  • 1
vladon
  • 8,158
  • 2
  • 47
  • 91
  • 1
    std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. A deterministic random number generator (e.g. a pseudo-random engine) has entropy zero. – Richard Critten May 08 '15 at 13:53
  • possible duplicate of [how to find the "true" entropy of std::random\_device?](http://stackoverflow.com/questions/28390843/how-to-find-the-true-entropy-of-stdrandom-device) – Cory Kramer May 08 '15 at 14:00
  • 1
    Well testing for randomness shouldn't be too hard if you go for the pragmatic approach I reckon. Just generate the random value like 10 times. If it's identical the odd's on that with a random device are practically zero. – laurisvr May 08 '15 at 21:07

1 Answers1

4

From cppreference's page on std::random_device::entropy (emphasis mine)

This function is not fully implemented in some standard libraries. For example, gcc and clang always return zero even though the device is non-deterministic. In comparison, Visual C++ always returns 32, and boost.random returns 10.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218