mardi 23 juin 2020

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:

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)?




Aucun commentaire:

Enregistrer un commentaire