C++11 Mersenne Twister 每次都产生相同的值

标签 c++ c++11 visual-c++ random

在您将此标记为重复之前(因为我知道这个问题已被多次询问)我已经阅读了 StackOverflow 上的数十个问题/答案以及许多其他“教程”等。

尽管遵循了我所知道的所有建议,但我的代码每次运行时都会生成相同的“随机”数字。在我看来,我没有做任何与我应该做的不同的事情。为什么这不起作用?

#include <random>
#include <iostream>
using namespace std;

random_device rd;     // used to initialise (seed) engine
mt19937 mt(rd());    // random-number engine used (Mersenne-Twister in this case)
uniform_int_distribution<int> dist(1, 4); // guaranteed unbiased

稍后在代码中/函数内:

for (it : vec_one) {
    int rand_int = dist(mt); // Generate Random Number
    switch (rand_int) 
    {
    case 1:
        cout << "One!" << endl;
    case 2:
        cout << "Two!" << endl;
    case 3:
        cout << "Three!" << endl;
    case 4:
        cout << "Four!" << endl;
    default:
        break;
    }
}

来自评论的回答 switch 语句中缺少中断。真的就这么简单。发电机工作正常。我忘了把它们包括在我过度疲劳的状态中,感觉很愚蠢。 但是…… 跳过这个问题的评论和答案的数量突出了它是多么容易做到。我现在感觉不那么傻了……

最佳答案

从技术上讲,这是有效的行为。来自 cppreference :

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.

如果您更喜欢标准的引用,请访问 [rand.device]/2:

If implementation limitations prevent generating non-deterministic random numbers, the implementation may employ a random number engine.

random_device::entropy()应该用于检查这一点,但不幸的是它没有在大多数库中正确实现,如链接文档所述(我可以确认它适用于 GCC 6.3、Clang 3.9 和 MSVC 2015)。

关于C++11 Mersenne Twister 每次都产生相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42685506/

相关文章:

c++ - 从spinbox保存数据

c++ - 在 read() 上阻塞时线程 'disappears' 我该如何调试它?

c++ - 隐式转换为左值引用

c++ - 具有不同接口(interface)的策略类

c++ - 运行时检查失败 #2 - 变量 'numberchoices' 周围的堆栈已损坏

visual-studio - 对 Visual Studio C++ 项目使用/Zi vs/Z7 有什么影响?

c - 得到一个奇数,太奇怪了

C++生成随机数-1

c - 二维数组的 malloc 在 GCC 中有效,但在 Visual C++ 中无效

c++ - 是否有用于 Visual Studio 的工具来跟踪(或中断)变量值?