Recommended way to initialize srand?

前端 未结 15 1652
夕颜
夕颜 2020-11-22 08:07

I need a \'good\' way to initialize the pseudo-random number generator in C++. I\'ve found an article that states:

In order to generate random-like

15条回答
  •  囚心锁ツ
    2020-11-22 08:38

    C++11 random_device

    If you need reasonable quality then you should not be using rand() in the first place; you should use the library. It provides lots of great functionality like a variety of engines for different quality/size/performance trade-offs, re-entrancy, and pre-defined distributions so you don't end up getting them wrong. It may even provide easy access to non-deterministic random data, (e.g., /dev/random), depending on your implementation.

    #include 
    #include 
    
    int main() {
        std::random_device r;
        std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
        std::mt19937 eng(seed);
    
        std::uniform_int_distribution<> dist{1,100};
    
        for (int i=0; i<50; ++i)
            std::cout << dist(eng) << '\n';
    }
    

    eng is a source of randomness, here a built-in implementation of mersenne twister. We seed it using random_device, which in any decent implementation will be a non-determanistic RNG, and seed_seq to combine more than 32-bits of random data. For example in libc++ random_device accesses /dev/urandom by default (though you can give it another file to access instead).

    Next we create a distribution such that, given a source of randomness, repeated calls to the distribution will produce a uniform distribution of ints from 1 to 100. Then we proceed to using the distribution repeatedly and printing the results.

提交回复
热议问题