随机数生成器始终生成相同的数字

编程入门 行业动态 更新时间:2024-10-27 19:28:59
本文介绍了随机数生成器始终生成相同的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用下面的代码用随机数填充数组

I am trying to fill my array with random numbers using the following piece of code

#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,我总是得到相同的输出

For n = 5, I always get the same output

562 726 348 916 6

对于n = 6,我总是得到相同的输出

For n = 6, I always get the same output

562 726 348 916 6 594

这些数字是随机的,我还检查了熵

These numbers arent random, I also checked the entropy

std:cout<<rd.entropy();

这给了我输出

0

我做错了什么,如何在数组中获得随机数?

What am I doing wrong and how do I get random numbers in my array?

推荐答案

调用 std :: random_device 上的"> entropy()成员函数,以了解您的实现是否正确实现:

Call the entropy() member function on std::random_device to find out whether your implementation implements it properly:

std :: random_device可以根据实现定义的伪随机数引擎,如果非确定性来源(例如硬件设备)不可用于实施.在这种情况下,每个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.

(源)

如果是这种情况,请调用 entropy()将返回 0 :

If this is the case, a call to entropy() will return 0:

确定性随机数生成器(例如伪随机引擎)熵为零.

A deterministic random number generator (e.g. a pseudo-random engine) has entropy zero.

在这种情况下,您需要使用其他回退机制进行播种.例如,您可以像以前的C天一样使用基于时间的种子.

If that is the case, you need to use a different fallback mechanism for seeding. For instance, you could use a time-based seed like in the old C-days.

尤其是在台式机平台上,您应该希望将 std :: random_device 实施为适当的不确定源.如果不是这种情况,则您可能只是在使用标准库实现的旧版本.如果您认为该实现应支持不确定的 std :: random_device ,但不支持,请考虑向您的标准库维护者提交错误报告.

On desktop platforms in particular, you should expect std::random_device to be implemented as a proper non-deterministic source though. If this is not the case, you might just be using a very old version of the standard library implementation. If you have the feeling that the implementation should support non-deterministic std::random_device but it does not, consider filing a bug report with your standard library maintainer.

更多推荐

随机数生成器始终生成相同的数字

本文发布于:2023-11-08 08:09:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568829.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   生成器   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!