vendredi 31 juillet 2020

How to properly seed a mersenne_twister RNG with the maximum entropy in C++

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();
    }
}
}



Aucun commentaire:

Enregistrer un commentaire