我正在尝试使用以下代码用随机数填充我的数组
#include<iostream>
#include<random>
int main(){
int n = 5;
int list[10];
std::random_device rd;
std::mt19937 eng(rd());
std::uniform_int_distribution<> distr(0, 1000);
for(int i=0;i<n;i++)
list[i] = distr(eng);
std::cout<<"The list of elements is: ";
for(int i=0;i<n;i++)
std::cout<<list[i]<<" ";
}
对于 n = 5,我总是得到相同的输出
562 726 348 916 6
对于 n = 6,我总是得到相同的输出
562 726 348 916 6 594
这些数字不是随机的,我还检查了熵
std:cout<<rd.entropy();
这给了我输出
0
我做错了什么以及如何在数组中获取随机数?
最佳答案
调用entropy()
member function在 std::random_device
上查看您的实现是否正确实现了它:
std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.
( Source )
如果是这种情况,一个 call to entropy()
will return 0
:
A deterministic random number generator (e.g. a pseudo-random engine) has entropy zero.
如果是这种情况,您需要使用不同的回退机制进行播种。例如,您可以像在旧的 C-days 中那样使用基于时间的种子。
特别是在桌面平台上,您应该期望 std::random_device
被实现为一个适当的非确定性源。如果不是这种情况,您可能只是在使用非常旧版本的标准库实现。如果您觉得该实现应该支持非确定性 std::random_device
但事实并非如此,请考虑向您的标准库维护者提交错误报告。
关于c++ - 随机数生成器总是生成相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36566057/