Recommended way to initialize srand?

前端 未结 15 1657
夕颜
夕颜 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:51

    The real question you must ask yourself is what randomness quality you need.

    libc random is a LCG

    The quality of randomness will be low whatever input you provide srand with.

    If you simply need to make sure that different instances will have different initializations, you can mix process id (getpid), thread id and a timer. Mix the results with xor. Entropy should be sufficient for most applications.

    Example :

    struct timeb tp;
    ftime(&tp);   
    srand(static_cast<unsigned int>(getpid()) ^ 
    static_cast<unsigned int>(pthread_self()) ^ 
    static_cast<unsigned int >(tp.millitm));
    

    For better random quality, use /dev/urandom. You can make the above code portable in using boost::thread and boost::date_time.

    0 讨论(0)
  • 2020-11-22 08:52

    Best way is to use another pseudorandom number generator. Mersenne twister (and Wichmann-Hill) is my recommendation.

    http://en.wikipedia.org/wiki/Mersenne_twister

    0 讨论(0)
  • 2020-11-22 08:58

    if you need a better random number generator, don't use the libc rand. Instead just use something like /dev/random or /dev/urandom directly (read in an int directly from it or something like that).

    The only real benefit of the libc rand is that given a seed, it is predictable which helps with debugging.

    0 讨论(0)
提交回复
热议问题