To get uniform distribution you must divide with RAND_MAX
first
static_cast<int>(21*static_cast<double>(rand())/(RAND_MAX+1)) - 10
using
rand() % 21 - 10;
is faster and is often used in applications but the resulted distribution is not uniform. Function rand()
generates numbers from from 0
to RAND_MAX
. If RAND_MAX%21!=0
lower numbers are generated with higher probability.
You may also consider to use the modulo method but with dropping of some of the random numbers:
int randMax = RAND_MAX - RAND_MAX%21;
int p=RAND_MAX+1;
while(p>randMax)
p=rand();
x=p%21 - 10;
Edit (comments from Johannes and Steve):
When dividing with RAND_MAX
there are some numbers from the range which will be picked more often so the proper way to handle is to reject numbers which would lead to an uneven distribution on the target interval.
Using the Boost Random Library (mentioned by Danvil) all the problems with uniformity of random numbers are eliminated.