Possible Duplicate:
How to generate a random number from within a range – C
I saw the following code from programming pearls
int randint(int l, int u)
{ return l + (RAND_MAX*rand() + rand()) % (u-l+1);
}
Can anyone help me explain it?
Can we just use
return l + rand() % (u-l+1);
Thanks,
The problem with using
rand() % nto get a number between 0 and n-1 is that it has some bias when n is not an exact divisor of RAND_MAX. The higher the value of n, the stronger this bias becomes.To illustrate why this happens, let’s imagine that rand() would be implemented with a six-sided die. So RAND_MAX would be 5. We want to use this die to generate random numbers between 0 and 3, so we do this:
What’s the value of x for each of the six outcomes of rand?
As you can see, the numbers 0 and 1 will be generated twice as often as the numbers 2 and 3.
When your use case doesn’t permit bias, this is a better way to calculate a random number: