Why is the new random library better than rand()?
Contemporary concerns regarding rand() have sparked discussions about utilizing superior random number generation (RNG) procedures based on the engine-distribution paradigm, as opposed to the conventional std::rand() and modulo approach. To gain a first-hand understanding of rand()'s shortcomings, a quick experiment was conducted.
Two functions were created, getRandNum_Old() and getRandNum_New(), leveraging std::rand() and std::mt19937 with std::uniform_int_distribution respectively, to generate random numbers between 0 and 5. 960,000 random numbers were generated using each method, and the frequency of each number (0-5) was recorded. Standard deviation served as the metric, with a lower value indicating a more uniform distribution. The process was reiterated 1000 times, and the time taken for each iteration was measured.
Surprisingly, the distribution of rolls was similar in both methods. The new method was approximately 4x slower. It appeared that the speed gain came at the cost of minimal improvement in quality.
However, a crucial distinction lies in the RNG implementation itself. Many rand() implementations employ Linear Congruential Generators (LCGs), which are generally not the most robust. Despite their prevalence, they typically produce acceptable results in basic tests like the one conducted.
The shortcomings of subpar rand() implementations include low randomness in low-order bits, short periods, low RAND_MAX, and correlation between successive extractions. However, it's crucial to note that these limitations are not inherent to the rand() API.
The underlying issue with rand() centers on:
The new
Performance-wise, std::mt19937 (used by std::rand() in your test) is slower than std::minstd_rand (an LCG also available in the
The above is the detailed content of Why is the `` library in C preferred over `rand()`?. For more information, please follow other related articles on the PHP Chinese website!