首頁 >後端開發 >C++ >為什麼新的 C 隨機函式庫比 std::rand() 更好?

為什麼新的 C 隨機函式庫比 std::rand() 更好?

Patricia Arquette
Patricia Arquette原創
2024-10-29 19:20:30582瀏覽

Why is the new C   random library a better choice than std::rand()?

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 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 主題encapsulates state within objects, allowing for thread-safe usage and reproducible sequences.

3. Cross-Platform Consistency:

Performance Compfmmson

Example

To demonstrate the difference, consider the follo follo🎜 >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

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; }

以上是為什麼新的 C 隨機函式庫比 std::rand() 更好?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn