GeekInterview.com
Series: Subject: Topic:
Question: 178 of 589

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

Asked by: Golda | Member Since Sep-2007 | Asked on: Sep 13th, 2007

View all questions by Golda

Showing Answers 1 - 2 of 2 Answers
sanjeev

Answered On : 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


  
Login to rate this answer.
kbjarnason

Answered On : Jul 1st, 2010

View all answers by kbjarnason

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.

  
Login to rate this answer.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

Related Open Questions

Ads

Connect

twitter fb Linkedin GPlus RSS

Ads

Interview Question

 Ask Interview Question?

 

Latest Questions

Interview & Career Tips

Get invaluable Interview and Career Tips delivered directly to your inbox. Get your news alert set up today, Once you confirm your Email subscription, you will be able to download Job Inteview Questions Ebook . Please contact me if you there is any issue with the download.