vla*_*don 5 c++ random cross-platform c++11
假设我有这个跨平台的程序
#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;
}
Run Code Online (Sandbox Code Playgroud)
在Linux Mint 17.1上g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2它始终生成随机数:
$ 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
Run Code Online (Sandbox Code Playgroud)
但我怎么能确定,在任何系统上std::random_device都是随机的?例如,在Windows上,mingw-gcc它不是随机的(例如,请参阅此问题),它将在启动时生成相同的序列.但是从MSVC++(根据S. Lavavej)开始,从2013年开始,它是随机的.
我以为我可以这样做:
if (rd.entropy() != 0) {
// initialize some generator like mt19937 with rd()
}
else {
// use another seed generator (for example, time in milliseconds)
}
Run Code Online (Sandbox Code Playgroud)
即将rd.entropy()与0进行比较.但事实证明这是错误的.
我该如何测试std::random_device随机性?
来自cppreference的页面std::random_device::entropy(强调我的)
该功能在某些标准库中并未完全实现。例如,gcc 和 clang始终返回零,即使设备是不确定的。相比之下,Visual C++ 始终返回 32,而 boost.random 返回 10。
| 归档时间: |
|
| 查看次数: |
647 次 |
| 最近记录: |