Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling srand() twice in the same program [closed]

why is it when i call srand() at 2 very different points it cause numbers to not be random? Once i remove one of them it goes back to normal.

like image 628
noobcoder Avatar asked Jan 12 '23 05:01

noobcoder


2 Answers

It depends on how you call it. The purpose of srand() is to seed the pseudo-random number generator used by rand(). So when you call srand(i), it will initialise rand() to a fixed sequence which depends on i. So when you re-seed with the same seed, you start getting the same sequence.

The most common use case is to seed the generator just once, and with a suitable "random" value (such as the idiomatic time(NULL)). This guarantees makes it likely that you'll get different sequences of pseudo-random numbers in different program executions.

However, occasionally you might want to make the pseudo-random sequence "replayable." Imagine you're testing several sorting algorithms on random data. To get fair comparisons, you should test each algorithm on the exact same data - so you'll re-seed the generator with the same seed before each run.

In other words: if you want the numbers simply pseudo-random, seed once, and with a value as random as possible. If you want some control & replayability, seed as necessary.

like image 200
Angew is no longer proud of SO Avatar answered Jan 19 '23 02:01

Angew is no longer proud of SO


srand (seed);

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.

If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.

Each time rand() is seeded with srand(), it must produce the same sequence of values.

http://www.cplusplus.com/reference/cstdlib/srand/

http://en.cppreference.com/w/cpp/numeric/random/srand

like image 38
4pie0 Avatar answered Jan 19 '23 02:01

4pie0