how is this generating a random number?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
In the following line of code:

unsigned long int next = 1;

/* rand: return pseudo-random integer on 0..32767 */
int rand(void)
{
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}

/* srand: set seed for rand() */
void srand(unsigned int seed)
{
    next = seed;
}


Are 1103515245 and 12345 and 32768 just some random numbers being used here, or are these used for a purpose? If so, why these specific integers?
It's a (very poor quality by today's standards) linear congruential generator. The choice of the integers defines the generator's properties, and there have been plenty of research on which ones work better than others.

You can find a brief introduction to LCGs and this particular generator listed at http://en.wikipedia.org/wiki/Linear_congruential_generator (2nd google hit on 1103515245 for me, after the stack overflow question http://stackoverflow.com/questions/8569113/why-1103515245-is-used-in-rand)
Last edited on
Topic archived. No new replies allowed.