Should I use a random engine seeded from std::random_device or use std::random_device every time

后端 未结 6 1792
梦如初夏
梦如初夏 2020-12-30 00:16

I have a class that contains two sources of randomness.

std::random_device rd;
std::mt19937 random_engine;

I seed the std::mt19937

6条回答
  •  没有蜡笔的小新
    2020-12-30 00:31

    If you need randomness for a simulation or a game, then that you're doing is fine. Call the random device just once, and do everything else with a randomly seeded pseudo-RNG. As a bonus, you should store the seed value in a log file so you can later replay the pseudo-random sequence:

    auto const seed = std::random_device()();
    // save "seed" to log file
    std::mt19937 random_engine(seed);
    

    (For multiple threads, use the PRNG in the main thread to generate seeds for further PRNGs in the spawned threads.)

    If you need a lot of true randomness for cryptographic purposes, then a PRNG is never a good idea, though, since a long sequence of output contains a lot less randomness than true randomness, i.e. you can predict all of it from a small subset. If you need true randomness, you should collect it from some unpredictable source (e.g. heat sensors, user keyboard/mouse activity, etc.). Unix's /dev/random may be such a "true randomness" source, but it may not fill up very quickly.

提交回复
热议问题