What is the difference between the functions rand(), random(), srand() and randomize()?

sanjeev

• Sep 25th, 2007

RAND: Rand uses a multiplicative congruential random number generator with period232 to return successive pseudo-random numbers in the range 0 to RAND_MAX.
Return Value: Rand returns the generated pseudo-random number.

RANDOM(): Random returns a random number between 0 and (num-1).random(num) is a macro defined in STDLIB.H.

RANDOMIZE(): Randomize initializes the random number generator with a random value. Because randomize is implemented as a macro that calls the time function prototyped in TIME.H, you should include TIME.H when you use this routine

SRAND(): The random number generator is reinitialized by calling srand with an argument value of 1.The generator can be set to a new starting point by calling srand with a given seed number.

Return Value: None

• Jul 1st, 2010

The first difference is that random and randomize are not part of the standard C language, so we'll ignore them.

rand() produces a (pseudo) random integer in the range 0 to RAND_MAX.  There are no particular requirements on what algorithm is used, except that if it is seeded with the same value, it must produce the same sequence with the same starting point.

srand is used to provide the seed for rand.

Given the code:

int k;

for ( k = 0; k < 10; k++ )
{
int i, j;

srand(1);

for ( i = 0; i < 3; i++ )
{
j = rand();
printf( "%d   ", j );
}

printf( "n" );
}

Assume the results for the first line were 119  463  17295.  Because we re-seed the random number generator with the same value each time we produce a new line, we should get exactly the same values on each line.

If, however, we used a different seed value each time, or omitted the call to srand before each line, the sequence on each line should be different.

Send   Reset