dimanche 9 juillet 2023

Using operator>> to seed mt19937

In a blog post entitled "C++ Seeding Surprises," Melissa E. O'Neill reports that, "When std::seed_seq tries to “fix” high-quality seed data, it actually makes it worse."

So, if you have a good source of entropy, why not bypass seed_seq entirely?

That's what function seed_randomly() does below. It's taken from my rand_replacement repository on GitHub. It uses operator>> to overwrite all 624 state variables in mt19937.

template <typename ResultType>
class rand_replacement
{
public:
    using urbg_type = std::mt19937;
    using seed_type = typename std::mt19937::result_type;
private:
    urbg_type eng_{ seed_type{1u} };  // By default, rand() uses seed 1u.

    // ...

    void seed_randomly()
    {
        std::random_device rd;
        std::stringstream ss;
        for (std::size_t i{ std::mt19937::state_size }; i--;)
            ss << rd() << ' ';
        ss >> eng_;
    }
};

Is this a novel and interesting idea, or is it really foolish?

Regarding std::string_stream: I understand that it is relatively slow, but that's okay. Seeding should be an infrequent operation.

Regarding std::random_device: I understand that random_device may be deterministic on some systems, may block on other systems, and also that it has a checkered history with mingGW, but for now, at least, I am satisfied with it. My question is not about random_device; it is strictly focused on the idea of bypassing seed_seq using operator>>, a technique that could be used with any entropy source.

Are there any downsides?




Aucun commentaire:

Enregistrer un commentaire