从给定的种子在 C++ 中生成相同的随机数序列 [英] Generate the same sequence of random numbers in C++ from a given seed

查看:121
本文介绍了从给定的种子在 C++ 中生成相同的随机数序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using mt19937 to generate a random string from a given seed like this:

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;
}

我想保证随机数序列(以及由此生成的随机字符串)在相同架构的不同机器上是相同的,这应该是 这个问题的答案.

I want to guarantee that the sequence of random numbers (and hence the random string generated) is the same across different machines of the same architecture which should be the case as per the answers to this question.

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

However, when I rebuild the binary (without changing any dependency or library), the random number sequence changes for the same seed (compared to the sequence generated from the previous build with the same seed).

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

How do I generate a guaranteed sequence of random numbers from a given seed across different binaries on the same machine architecture+image (x86_64 Linux)?

推荐答案

If reproducible random"数字是你关心的东西,你应该避免 C++ 发行版,包括 uniform_int_distribution,而是依靠你自己的方式将随机数从 mt19937 转换成你想要的数字.(例如,我为统一整数提供了方法.请注意,有当可重复性很重要时要考虑的其他事项.)

If reproducible "random" numbers are something you care about, you should avoid C++ distributions, including uniform_int_distribution, and instead rely on your own way to transform random numbers from mt19937 into the numbers you desire. (For example, I give ways to do so for uniform integers. Note that there are other things to consider when reproducibility is important.)

C++ 分发类,例如 uniform_int_distribution没有标准的实现.因此,这些分发类可以在 C++ 标准库的不同实现中以不同方式实现.请注意,它不是编译器"、操作系统"或架构".决定使用哪种算法.另请参阅此问题.

C++ distribution classes, such as uniform_int_distribution, have no standard implementation. As a result, these distribution classes can be implemented differently in different implementations of the C++ standard library. Note that it's not the "compiler", the "operating system", or the "architecture" that decides which algorithm is used. See also this question.

另一方面,诸如mt19937之类的随机引擎确实有保证的实现;它们将为所有兼容的 C++ 库实现(包括不同架构"的实现)中的相同种子返回相同的随机数.

On the other hand, random engines such as mt19937 do have a guaranteed implementation; they will return the same random numbers for the same seed in all compliant C++ library implementations (including those of different "architectures").

这篇关于从给定的种子在 C++ 中生成相同的随机数序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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