Whats the difference between srand(1) and srand(0)

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
( "    d", 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




It is probably an implementation detail. The standard mandates that the random seed 1 is special, and the internal register of your specific random generator algorithm is probably zero-initialized, thus causing the same random sequence for seed(0) and seed(1). I'd even wager that the first line of your srand() implementation looks like:


if ( seed == 1 ) seed = 0;

to force standard-conformant behaviour.
Generally, the random number generators for rand() and srand() are not required to give different sequences for different seeds, but the same sequence for the same seed. So, don't rely on different seeds generating different random sequences, and you should be fine. If not, welcome to implementation-specific fun.

How glibc does it:

around line 181 of glibc/stdlib/random_r.c, inside function __srandom_r


  
 
if (seed == 0)
    seed
= 1;
posted @ 2011-11-08 21:53  Thomas Hwang  阅读(169)  评论(0编辑  收藏  举报