I know this might be a "old" question, but I want to focus on the probability.
My first question is:
in C, rand()
will give a number from 0
to RAND_MAX
, does each number in this interval have the same probability to be chosen by rand()
?
The second question:
if rand()
lets each number from 0
to RAND_MAX
to have the same (or approximately same) probability to be chosen, when I want to get a random number from 0 to N-1 (N-1 < RAND_MAX), I'll do this generally:
rand()%N
But if RAND_MAX
is NOT the multiple of N, the probability of random number chosen from 0 to N-1 might not be same
For instance, suppose RAND_MAX=150 and N=100, when I do rand()%100
, the number from 0 to 49 will have a higher probability to be chosen than the number from 50 to 99 because 150 is not the multiple of 100.
Is there a algorithm or function in C, which can let each random number have the same probability to be chosen?