The following code outputs a random number each second:
int main ()
{
srand(time(NULL)); // Seeds number generator with execution time.
while (true)
All the examples posted so far actually give badly distributed results. Execute the code often and create a statistic to see how the values become skewed.
A better way to generate a real uniform random number distribution in any range [0, N] is the following (assuming that rand
actually follows a uniform distribution, which is far from obvious):
unsigned result;
do {
result = rand();
} while (result > N);
Of course, that method is slow but it does produce a good distribution. A slightly smarter way of doing this is to find the largest multiple of N that is smaller than RAND_MAX
and using that as the upper bound. After that, one can safely take the result % (N + 1)
.
For an explanation why the naive modulus method is bad and why the above is better, refer to Julienne’s excellent article on using rand.