【问题标题】:std::random - On Windows always I get the same numbersstd::random - 在 Windows 上我总是得到相同的数字
【发布时间】:2021-04-23 14:20:24
【问题描述】:

编译后,程序总是返回相同的结果。出乎意料的是,代码在 Linux 上可以正常运行...

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distribut(1, 6);

    for (int i=0; i < 10; i++)
    {
        std::cout << distribut(gen) << ' ';
    }

编译器规范:

❯ g++ --version
g++.exe (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

【问题讨论】:

标签: c++ linux windows random g++


【解决方案1】:

这里的问题是 std::random_device 对象(您用来播种 std::mt19937可能每次都会产生相同的种子(尽管它不会在我的 Windows 10 + Visual Studio 测试平台)。

来自cppreference(我的粗体字):

std::random_device 可以根据 实现定义的伪随机数引擎,如果 非确定性源(例如硬件设备)不可用于 实施。 在这种情况下,每个 std::random_device 对象可能 生成相同的数列

这是一个可能的解决方案,使用对 time(nullptr) 的“经典”调用作为种子,这也避免使用“中间”std::random_device 对象来生成该种子(尽管还有其他选项来获取该种子):

#include <iostream>
#include <random>
#include <ctime>

int main()
{
    std::mt19937 gen(static_cast<unsigned int>(time(nullptr)));
    std::uniform_int_distribution<> distribut(1, 6);
    for (int i = 0; i < 10; i++) {
        std::cout << distribut(gen) << ' ';
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多