为什么这个随机数生成器生成相同的数字? [英] Why is this random number generator generating same numbers?

查看:201
本文介绍了为什么这个随机数生成器生成相同的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个起作用,但是第二个总是返回相同的值.为什么会发生这种情况,我应该如何解决呢?

The first one works, but the second one always returns the same value. Why would this happen and how am I supposed to fix this?

int main() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(0, 1);

    for(int i = 0; i < 10; i++) {

        std::cout << dis(gen) << std::endl;
    }return 0;
}

一个不起作用:

double generateRandomNumber() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(0, 1);

    return dis(gen);
}



int main() {
    for(int i = 0; i < 10; i++) {
        std::cout << generateRandomNumber() << std::endl;
    }return 0;
}

推荐答案

您正在使用什么平台?如果不存在用于生成随机数的硬件或操作系统功能,则允许std::random_device为伪RNG.它可能会使用当前时间进行初始化,在这种情况下,您调用它的时间间隔可能相隔太近,以至于当前时间"无法采用其他值.

What platform are you working on? std::random_device is allowed to be a pseudo-RNG if hardware or OS functionality to generate random numbers doesn't exist. It might initialize using the current time, in which case the intervals at which you're calling it might be too close apart for the 'current time' to take on another value.

尽管如此,如评论中所述,它并不意味着以这种方式使用.一个简单的解决方法是将rdgen声明为static.一个适当的解决方法是将RNG的初始化移出需要随机数的函数,以便它也可以被需要随机数的其他函数使用.

Nevertheless, as mentioned in the comments, it is not meant to be used this way. A simple fix will be to declare rd and gen as static. A proper fix would be to move the initialization of the RNG out of the function that requires the random numbers, so it can also be used by other functions that require random numbers.

这篇关于为什么这个随机数生成器生成相同的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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