[英]Generate the same sequence of random numbers in C++ from a given seed
I am using mt19937 to generate a random string from a given seed like this:我正在使用 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;
}
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).但是,当我重建二进制文件(不更改任何依赖项或库)时,相同种子的随机数序列会发生变化(与使用相同种子的先前构建生成的序列相比)。
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)?如何从同一机器架构+映像(x86_64 Linux)上的不同二进制文件中的给定种子生成有保证的随机数序列?
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.如果您关心可重现的“随机”数,则应避免使用 C++ 分布,包括uniform_int_distribution
,而是依靠您自己的方式将随机数从mt19937
转换为您想要的数字。 (For example, I give ways to do so for uniform integers . Note that there are other things to consider when reproducibility is important.) (例如,我给出了统一整数的方法。请注意,当可重复性很重要时,还有其他事情需要考虑。)
C++ distribution classes, such as uniform_int_distribution
, have no standard implementation . C++ 分布类,例如uniform_int_distribution
, 没有标准实现。 As a result, these distribution classes can be implemented differently in different implementations of the C++ standard library.因此,这些分发类可以在 C++ 标准库的不同实现中以不同方式实现。 Note that it's not the "compiler", the "operating system", or the "architecture" that decides which algorithm is used.请注意,决定使用哪种算法的不是“编译器”、“操作系统”或“架构”。 See also this question .另请参阅此问题。
On the other hand, random engines such as mt19937
do have a guaranteed implementation;另一方面,像mt19937
这样的随机引擎确实有保证的实现; they will return the same random numbers for the same seed in all compliant C++ library implementations (including those of different "architectures").它们将在所有兼容的 C++ 库实现(包括不同“架构”的实现)中为相同的种子返回相同的随机数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.