我使用以下代码测试 C++ <random>
图书馆。
为什么每次运行已编译的可执行文件都会得到完全相同的序列?是 rd()
编译时确定性?如何为每次运行获得不同的输出?
Windows 7 64 位上的 GCC 4.8.1。使用来自 http://nuwen.net/mingw.html 的 MinGW 分发.
编辑:我用 Visual Studio 测试了相同的代码。没有问题。输出是不确定的。这可能是我使用的 mingw gcc 4.8.1 中的一个错误。
#include <iostream>
#include <random>
using namespace std;
int main(){
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dist(0,99);
for (int i = 0; i< 16; ++i){
cout<<dist(mt)<<" ";
}
cout <<endl;
}
最佳答案
来自 http://en.cppreference.com/w/cpp/numeric/random/random_device :
Note that std::random_device may be implemented in terms of a pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation.
不过,我希望一个体面的实现至少可以为 RNG 播种。
编辑:我怀疑他们故意选择每次都提供相同的序列,以表明流并不像 promise 的那样随机。
关于c++ - 为什么每次使用 std::random_device 和 mingw gcc4.8.1 运行都会得到相同的序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61282593/