Why is the new random library better than std::rand()?
Introduction
The std::rand() function has historically been the go-to random number generator in C . However, the newer std::random library offers numerous advantages over std::rand(), including:
1. Improved Randomness:
Std::rand() uses a simple linear congruential generator (LCG), which can be predictable and prone to statistical bias. On the other hand, the new library provides access to更高质量的随机数生成器 (PRG),例如 Mersenne Twister,具有更好的均匀分布和更长的周期。
2. Encapsulation of State:
Std::rand() uses global state, making it difficult to use in多线程环境and ensuring reproductibility. The new library encapsulates state within objects, allowing for thread-safe usage and reproducible sequences.
3. Cross-Platform Consistency:
Implementations of std::rand() vary across platforms, leading to inconsistent behavior. The new library provides standardized algorithms, ensuring consistent output regardless of the platform.
Performance Comparison
While the new library provides numerous benefits, it is not necessarily faster than std::rand(). In fact, some implementations of std::rand() are highly optimized for performance. However, this optimization is often made at the expense of randomness. If randomness is more important to you than performance, then the new library is the better choice.
Example
To demonstrate the difference, consider the following experiment:
<code class="cpp">int old_min = 999999; int old_max = 0; int new_min = 999999; int new_max = 0; for(int i = 0; i<100000; i++){ int r1 = std::rand() % 100; int r2 = my_random_engine() % 100; if(r1 > old_max) old_max = r1; if(r1 < old_min) old_min = r1; if(r2 > new_max) new_max = r2; if(r2 < new_min) new_min = r2; }</code>
Running this experiment will show that the new random library produces a more evenly distributed set of numbers with a wider range than std::rand().
Conclusion
While std::rand() is a convenient and performant option for generating random numbers, it has limitations in terms of randomness and multithreading. The new std::random library addresses these limitations, providing a more robust and reliable approach to generating random numbers in C .
以上是为什么新的 C 随机库比 std::rand() 更好?的详细内容。更多信息请关注PHP中文网其他相关文章!