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?
How often should I call srand() in a C++ application?
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).
Boost::random is more portable than drand48_r, or use the C++0x random (which is a Boost derivative) –
Climb
@MSalters: Of course, I'd go for the new
<random>
features any day. They're just a little more involved to set up, so I thought I answer in the spirit of the question -- but indeed, do use <random>
if you can! –
Slather Thanks for this very complete answer. –
Shalne
"If you reseed often, you might actually break some of the statistical properties of the random numbers." Some evidence to back up this claim would be very welcome. –
Hypersonic
@Theod'Or: By omission: RNGs don't generally make guarantees about their initial value relative to the seed, but only to the statistics of a rollout starting at (any) one fixed seed. –
Slather
No just calling once is fine. Use the seed value to make the random sequence the same on each execution. This could be useful in making (for example) a game's behaviour deterministic when you replay it for debugging.
© 2022 - 2024 — McMap. All rights reserved.
srand
does not makerand
"more" random. It doesn't ensure "reasonable randomness" in any way. It just makes the sequence of random numbers start from the specified point. – Unnaturalrand()
is a linear congruential generator, and as their illustration shows, a new seed, if it does not match a number the generator would produce with the previous seed, will result in a different sequence of numbers. If the seed matches though, only the starting point changes. – Hypersonicrand()
is no longer a simple linear congruential generator. – Hypersonic