Search code examples
c++c++11randomboostboost-multiprecision

Is it possible to set a deterministic seed for boost::random::uniform_int_distribution<>?


I'm using boost::random::uniform_int_distribution<boost::multiprecision::uint256_t> to generate some unit tests. Notice that I'm using multiprecision, which is why I need to use boost and not the standard library. For my periodic tests, I need to generate deterministic results from a nondeterministic seed, but in such a way where I can reproduce the results later in case the tests fail.

So, I would generate a true random number and use as a seed, and inject that to uniform_int_distribution. The purpose is that if this fails, I'll be able to reproduce the problem with the same seed that made the tests fail.

Does this part of boost support generating seed-based random numbers in its interface? If not, is there any other way to do this?

The way I generate random numbers currently is:

boost::random::random_device                                              gen;
boost::random::uniform_int_distribution<boost::multiprecision::uint256_t> dist{100, 1000};
auto random_num = dist(gen);

PS: Please be aware that the primary requirement is to support multiprecision. I require numbers that range from 16 bits to 512 bits. This is for tests, so performance is not really a requirement. I'm OK with generating large random numbers in other ways and converting them to boost::multiprecision.


Solution

  • The boost::random::random_device is a Non-deterministic Uniform Random Number Generator, a true random number generator. Unless you need real non-deterministic random numbers you could use a Pseudo-Random Number Generator (at least for testing purposes), which can be seeded. One known Pseudo-Random Number Generator is the mersenne twister boost::random::mt19937.

    This generator usually gets seeded by a real random number which you could print for reproducability in your unit tests:

    auto seed = boost::random::random_device{}();
    std::cout << "Using seed: " << seed << '\n';
    boost::random::mt19937 gen{ seed };
    boost::random::uniform_int_distribution<boost::multiprecision::uint256_t> dist{100, 1000};
    auto random_num = dist(gen);