Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test std::random_device for randomness?

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?

like image 600
vladon Avatar asked Sep 28 '22 00:09

vladon


1 Answers

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.

like image 117
Cory Kramer Avatar answered Oct 05 '22 08:10

Cory Kramer