Non-reproducible random numbers using `<random>`

void setseed(int newSeed) {
        re.seed(newSeed);
        dud.reset(); // <---- 
        dnd.reset(); 
    };

Distributions have internal state. You need to reset it in order to get the same sequence again.


If reproducible "random" numbers are something you care about, you should avoid C++ distributions, including uniform_real_distribution and normal_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 floating-point numbers. Note that there are other things to consider when reproducibility is important.)

C++ distribution classes, such as uniform_real_distribution, have no standard implementation. As a result, even if the same seed is passed to these distributions, the sequence of numbers they deliver can vary, even from run to run, depending on how these distributions are implemented. Note that it's not the "compiler", the "operating system", or the "architecture" that decides which algorithm is used, but rather the C++ standard library implementation decides. See also this question.

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, even across runs, in all compliant C++ library implementations (including those of different "architectures").

See also this question: Generate the same sequence of random numbers in C++ from a given seed.

Tags:

C++

Random