假设我有这个跨平台程序
#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/