c++ - 如何测试 std::random_device 的随机性?

标签 c++ c++11 random cross-platform

假设我有这个跨平台程序

#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;
}

在带有 g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 的 Linux Mint 17.1 上,它总是产生随机数:

$ 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 

但我如何确定在任何系统上 std::random_device 都是随机的?例如,在带有 mingw-gcc 的 Windows 上,它不是是随机的(参见,例如 this question),它会在启动时产生相同的序列。但是从 2013.4 开始,在 MSVC++ 上(根据 S.Lavavej),它是随机的。

我认为我可以做到这一点:

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

即将 rd.entropy() 与 0 进行比较。但事实证明这是错误的。

如何测试 std::random_device 的随机性?

最佳答案

来自 cppreference std::random_device::entropy 上的页面(强调我的)

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.

关于c++ - 如何测试 std::random_device 的随机性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30125518/

相关文章:

C++ 运算符重载

windows - Windows 上的 C++11 线程

jquery - 为具有相同类别的 div 随机添加类别

kotlin - 如何使用随机 bool 值生成器生成均匀的随机整数生成器?

c++ - 如何在 C++ 中将 int[][] 转换为 int**

c++ - ARC 不允许隐式转换 Objective-C 指针

c++ - 是否有用于阻塞 boost::asio TCP 连接的 boost::iostreams(双向)设备?

c++ - unsigned short + int 类型是实现定义的吗?

c++ - 跨平台线程亲和函数

python - 在 python 中生成 1,000,000+ 随机数的最快方法