I just found out the hard way that srand(1)
resets the PRNG of C(++) to the state before any call to srand
(as defined in the reference).
However, the seed 0 seems to do the same, or the state before any call to srand
seems to use the seed 0.
What’s the difference between those two calls or what is the reason they do the same thing?
For example this code (execute on Ideone)
#include <stdio.h>
#include <stdlib.h>
int main() {
for (int seed = 0; seed < 4; seed++ ) {
printf( "Seed %d:", seed);
srand( seed );
for(int i = 0; i < 5; i++ )
printf( " %10d", rand() );
printf( "\n");
}
return 0;
}
returns
Seed 0: 1804289383 846930886 1681692777 1714636915 1957747793
Seed 1: 1804289383 846930886 1681692777 1714636915 1957747793
Seed 2: 1505335290 1738766719 190686788 260874575 747983061
Seed 3: 1205554746 483147985 844158168 953350440 612121425
Neither the C nor the C++ standards say much about the specifics of the implementation of
rand()
andsrand()
. The details are left almost entirely up to the implementor. The C standard requires that:but it does not contain any requirement that different seeds must produce different sequences. Apparently, on your system, seeds of zero and one have the same effect. I would guess that this is to provide backwards compatibility with some piece of software that expects
srand(0)
to reset the PRNG to its initial state.When reading manual pages, they all state that "If no seed value is provided, the rand() function is automatically seeded with a value of 1." This is probably why the reference page you link to states that seeding with 1 resets the state.
That the same result happens for seeding with both 0 and 1 is most likely implementation dependant, and should not be counted on happening on all platforms.
How glibc does it:
But that's just how glibc does it. It depends on the implementation of the C standard library.
The srand() function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand() is called before any calls to srand() are made, the same sequence shall be generated as when srand() is first called with a seed value of 1.
Maybe useful: http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html
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. Taken from the srand reference
The reason 1 is specified is because some random number generators will get stuck at zero if the seed is set to zero. For example shift-registers and Multiplicative congruential types i.e.
r(n+1) = (A * r(n))mod M
.Many C implementations use Linear Congruential
r(n+1) = (A * r(n) + B) mod M
, B <> 0 which don't get stuck.