0

I want to fully seed a Mersenne twister with the maximum amount of entropy possible (not just 32 bits). Is this the correct way? Is there a better way to do this? Will this work for every kind of standard C++ random number generator or is there a simple way to make one that is?

#include <algorithm>
#include <array>
#include <bitset>
#include <functional>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>

int main() {
    using RNG = std::mt19937_64;
    auto constexpr state_size = RNG::state_size;

    std::array<std::seed_seq::result_type, state_size> entropy;
    std::random_device rdev;
    std::generate_n(entropy.begin(), state_size, std::ref(rdev));
    std::seed_seq seed(entropy.begin(), entropy.end());
    RNG rng(seed);

    auto constexpr n = 16U;
    using data_t = std::uint64_t;

    std::array<data_t, n> data;
    std::generate_n(data.begin(), n, std::ref(rng));

    for (auto d : data) {
        std::cout << std::bitset<8 * sizeof(data_t)>(d).to_string();
    }
}
user1032677
  • 363
  • 2
  • 11
  • years ago i used the Mersenne Twister... I made the user move their mouse all over the screen to generate entropy. I know this doesn't help you, but it's late and i wanted to tell you a story. – Andy Aug 01 '20 at 05:22
  • 1
    No, that won't always work, and no, doing it in a portable, reliable way is [anything but simple](https://www.pcg-random.org/posts/simple-portable-cpp-seed-entropy.html). – Miles Budnek Aug 01 '20 at 05:43
  • @PeterO. So basically, I can't use std::random_device since it can fall back to a deterministic method of generating entropy? – user1032677 Aug 01 '20 at 06:10
  • I'm just going to use Boost until the standard library has better support. – user1032677 Aug 01 '20 at 06:17
  • According to the C++ Standard, `random_device` allows the implementation to "employ a random number engine" if it can't generate "nondeterministic" random numbers due to "implementation limitations" ([rand.device]). Effectively, it can fall back this way without much warning. See also [this answer](https://stackoverflow.com/questions/53185702/why-is-this-random-number-generator-generating-same-numbers/53198298#53198298). – Peter O. Aug 01 '20 at 06:17

0 Answers0