srand(0) and srand(1) give the same results?

1.7k Views Asked by At

srand(0) and srand(1) give the same results. srand(2), srand(3), etc. give different results.

Any reason why seed = 0 and seed = 1 yield the same random sequence?

Can't find an explanation in the man page. Only that if a seed is not provided, seed = 1 is used.

Thanks.

4

There are 4 best solutions below

0
On BEST ANSWER

Within the glibc sources for srandom_r (which is aliased to srand), line 179:

/* We must make sure the seed is not 0.  Take arbitrarily 1 in this case.  */
if (seed == 0)
    seed = 1;

It's just an arbitrary decision basically.

1
On

The function srand() is used to initialize the pseudo-random number generator by passing the argument seed.

So if the seed is set to 1 then the generator is reinitialized to its initial value. Then it will produce the results as before any call to rand and srand.

so srand(1) actually represent the result srand(0).

0
On

Depends on compiler!

srand(0);
int a=rand(),b=rand();
srand(1);
int c=rand(),d=rand();

VC 2005 result:

a    0x00000026    int
b    0x00001e27    int
c    0x00000029    int
d    0x00004823    int
0
On

This is an implementation dependent behaviour.

For instance, POSIX.1-2001 gives the following example of an implementation of rand() and srand()

static unsigned long next = 1;

/* RAND_MAX assumed to be 32767 */
int myrand(void) {
    next = next * 1103515245 + 12345;
    return((unsigned)(next/65536) % 32768);
}

void mysrand(unsigned seed) {
    next = seed;
}

Now, if you use this implementation you will end up with:

0
16838

for srand(0) and srand(1) respectively.

ref.: http://linux.die.net/man/3/rand

I ran into a quite similar problem before, where rand() yielded different sequences for the same seed across different platforms. Lesson learned, portable code should implement his own PRNG.