C ++使用default_random_engine在循环中生成随机数 [英] C++ generating random numbers in a loop using default_random_engine

查看:473
本文介绍了C ++使用default_random_engine在循环中生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我正在尝试一个程序,该程序使用#include<random>中定义的random engines在C ++中生成随机数.我的程序如下:-

Recently I was trying out a program on generating random numbers in C++ using the random engines defined in #include<random>. My program goes as follows :-

#include <iostream>
#include <random>
#include <chrono>
using namespace std;
int random (int lim)
{
    default_random_engine dre (chrono::steady_clock::now().time_since_epoch().count());
    uniform_int_distribution<> uid(1,lim);
    return uid(dre);
}
int main()
{
    for (int i=0;i<10;++i)
    cout<<random(100)<<" ";
    return 0;
}

很简单,绝对可以!但是,当我尝试输出时,这些数字的随机性较低:-

Simple, definitely ! But when I tried the output the numbers were less random like these :-

66 95 95 96 96 96 96 96 97 97

当我略微更改程序时,将default_random_engine声明为static或将其设置为global,则我的输出是正确的,例如:-

When I changed my program slightly & declared the default_random_engine as static or made it global then my output was proper such as this :-

62 53 21 38 7 51 46 40 86 12

任何人都可以指出我的程序最初实际出了什么问题吗?小小的变化如何帮助我获得更好的输出?

Could anyone point out what actually was going wrong in my program initially & how did the small change help me get a better output ?

推荐答案

每次运行random时,都使用相同或非常接近相同的种子来重新生成生成器的种子,因此每次迭代或如果迭代得到的结果都是相同的改变不会太大.

Every time you run random you reseed the generator with the same or very close to the same seed so you get the same output each iteration or if it does change it will not be by much.

要解决此问题,您只需为生成器播种一次,然后继续调用它即可.通过将其设为静态,生成器将按预期工作,因为只有在您继续使用它的随机序列而不是获取它将创建的第一个随机数时,才创建并生成该生成器.

To fix this you only seed the generator once and then keep calling it. By making it static it works as expected as the generator is only created and seeded once you so keep going on its random sequence instead of getting the first random number it would create.

通常,随机数生成器具有通过算法输入的内部值,算法吐出的值是它们为随机数返回的值.然后保留该数字以用于算法的下一次迭代.这就是我们获得随机序列的方式.

Typically random number generators have an internal value that they put through an algorithm and what the algorithm spits out is what they return for a random number. That number is then retained for the next iteration of the algorithm. This is how we get an random sequence.

如果我们使用相同的种子,我们将获得与从相同编号开始的相同输出序列.在您的情况下,每次chrono::steady_clock::now()前进时,您的种子就只会更改,并且循环的运行速度比那快,因此每次调用都获得相同的时间(种子).

If we use the same seed we will get the same output sequence as we start from the same number. In your case your seed will only change each time chrono::steady_clock::now() advances and your loop is running faster than that so you are getting the same time(seed) each call.

这篇关于C ++使用default_random_engine在循环中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆