問題描述
我有一個 C++ 應用程序,它在不同的地方調用 rand().我是否需要定期初始化 srand()
以確保 rand() 是合理隨機的,還是在應用程序啟動時調用一次就足夠了?
I have a C++ application which calls rand() in various places. Do I need to initialize srand()
regularly to ensure that rand() is reasonably random, or is it enough to call it once when the app starts?
推薦答案
如果您只有一個線程,請一次.如果您經常重新播種,實際上可能會破壞隨機數的某些統計特性.如果您有多個線程,則根本不要使用 rand
,而是使用諸如 drand48_r
之類的線程安全的東西,它可以讓您保持每個線程的狀態(因此您可以播種一次每個線程).
If you have only a single thread, seed once. If you reseed often, you might actually break some of the statistical properties of the random numbers. If you have multiple threads, don't use rand
at all, but rather something threadsafe like drand48_r
, which lets you maintain a per-thread state (so you can seed once per thread).
這篇關于在 C++ 應用程序中,我應該多久調用一次 srand()?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!