Programmer
Programmer

Reputation: 6753

Understanding the rand() operation

At http://www.cplusplus.com/reference/clibrary/cstdlib/rand/ , I read the following : This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using srand.

What does seed mean and how does rand() use seed to generate the series?

Upvotes: 3

Views: 328

Answers (2)

perreal
perreal

Reputation: 97948

Very crudely, it is something like:

   int rand() {
       return last_random_val = 
          ((last_random_val * 1103515245) + 12345) & 0x7fffffff);
   }

   void srand(int seed) {
        last_random_val = seed;
   }

And the last_random_val is set to the seed when you call srand(). Hence, for the same seed, same sequence of numbers are generated.

Upvotes: 2

Joey
Joey

Reputation: 354536

rand() uses a so-called pseudo-random number generator. It generates not really random numbers but a deterministic sequence that appears to look random enough and satisfy some statistical properties. The seed is essentially the starting value of that sequence; given the same seed, the PRNG will always produce the same sequence. That is why you often seed with something that is not too deterministic, e.g. the current time (although that fails if you re-seed the PRNG in a tight loop or run the program fast enough in succession or parallel).

In most cases the PRNG in C is a simple linear congruential generator. It calculates the next number in a sequence with the following equation:

enter image description here

a and b here are values that have to be chosen with care to avoid horrible results. For example, for obvious reasons 2 is a very very bad choice for a. c just reduces the number to a certain range and is often a power of two. The seed simply supplies the 0th value.

Upvotes: 7

Related Questions