【问题标题】:Generate the same sequence of random numbers in C++ from a given seed从给定的种子在 C++ 中生成相同的随机数序列
【发布时间】:2020-10-13 18:16:52
【问题描述】:

我正在使用 mt19937 从给定的种子生成随机字符串,如下所示:

std::string StringUtils::randstring(size_t length, uint64_t seed) {
    static auto& chrs = "abcdefghijklmnopqrstuvwxyz";

    thread_local static std::mt19937 rg(seed);
    thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2);

    std::string s;
    s.reserve(length);

    while(length--) {
        s += chrs[pick(rg)];
    }

    return s;
}

我想保证随机数序列(以及因此生成的随机字符串)在相同架构的不同机器上是相同的,这应该是the answers to this question的情况。

但是,当我重建二进制文件(不更改任何依赖项或库)时,相同种子的随机数序列会发生变化(与先前使用相同种子生成的序列相比)。

如何在同一机器架构+映像 (x86_64 Linux) 上跨不同二进制文件从给定种子生成有保证的随机数序列?

【问题讨论】:

标签: c++ random deterministic mersenne-twister


【解决方案1】:

如果您关心可重现的“随机”数字,您应该避免使用 C++ 发行版,包括 uniform_int_distribution,而是依靠您自己的方式将伪随机数字从 mt19937 转换为您想要的数字。 (例如,我为uniform integers 提供了这样做的方法。请注意,当可重复性很重要时,还有other things to consider。)

C++ 分发类,例如uniform_int_distributionhave no standard implementation。因此,这些分发类可以在 C++ 标准库的不同实现中以不同方式实现。请注意,决定使用哪种算法的不是“编译器”、“操作系统”或“架构”。另见this question

另一方面,mt19937 等随机引擎确实有保证的实现;它们将为所有兼容的 C++ 库实现(包括不同“架构”的实现)中的相同种子返回相同的伪随机数。例外是default_random_engine

【讨论】:

    猜你喜欢
    • 2022-08-17
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多