函数中的随机整数总是返回相同的数字 - 为什么? [英] Random integers from a function always return the same number - why?

查看:55
本文介绍了函数中的随机整数总是返回相同的数字 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 C++,有一个关于 random_device 的问题.

I'm currently learning C++ and have a question about the random_device.

我正在尝试模拟蒙蒂厅问题.为此,我需要随机整数来选择随机门.因此,我尝试制作一个返回随机整数的函数.

I'm trying to simulate the monty hall problem. For this I need random integers to pick random doors. Therefore I tried making a function that returns random integers for this purpose.

int guessGetRandomIndex() {
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(0, 2);
    return distr(eng);

然而,当我尝试在 main() 中获取随机整数时,我不断得到相同的数字.

However when I try to get random integers in main() I keep getting same numbers.

    vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto & j : v){
    int random = guessGetRandomIndex();
    std::cout << random << ' ';
}    
 Output: 1 1 1 1 1 etc.

但是,当我将随机设备放在主循环中并在那里执行相同操作时,我设法获得了随机整数.

However when I put the random device in the main loop and do the same there I manage to get random integers.

    std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(rd()); // seed the generator
std::uniform_int_distribution<> distr(0, 2); // define the range
vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto & j : v){

    std::cout << distr(eng) << ' ';
}   

 Output: 1 2 1 2 0 1

这是为什么?我只是想封装随机设备.我认为每次调用类似于 Python 的 random.randint 函数时它都会生成新的随机数,但我认为 C++ 中还有其他事情发生.

Why is that? I'm simply trying to encapsulate the random device. I thought it would generate new random number each time the function is called similiar to Pythons random.randint but I reckon there is something else going on in C++.

提前致谢.

推荐答案

您每次都在创建一个新的 std::random_devicestd::mt19937 生成器调用 guessGetRandomIndex.将它们标记为 static 或通过引用将它们传递给函数以避免重新实例化它们:

You're creating a new std::random_device and std::mt19937 generator every time you call guessGetRandomIndex. Mark them as static or pass them to the function via reference to avoid re-instantiating them:

int guessGetRandomIndex() {
    static std::random_device rd; // obtain a random number from hardware
    static std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(0, 2);
    return distr(eng);
}

为了生成伪随机数,标准库提供的生成器包含一个内部状态,每次生成一个值时都会发生变化.如果你不断地重新实例化一个生成器,内部状态将始终与其初始状态匹配,因此总是生成相同的数字.

In order to generate pseudorandom numbers, the generators provided by the standard library contain an internal status that varies every time they generate a value. If you keep re-instantiating a generator, the internal state will always match its initial one, thus always generating the same number.

这篇关于函数中的随机整数总是返回相同的数字 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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