Tag Archives: uniform distribution

Generate uniformly distributed random variables

Formulas shown below generate values that follow uniform distribution.

Using simple modulo methods is not considered as a good solution (although used a lot by students) as the module function does not generate all the variables with the same frequency.

Random integer between [ 0, 1 ]

int r = (int) (rand()/(RAND_MAX + 0.0));

Random integer between [ 0, 1 )

int r = (int) (rand()/(RAND_MAX + 1.0));

Random integer between [ 0, N ]

int r = (int) (N * (rand() / (RAND_MAX + 0.0)));

Random integer between [ 0, N )

int r = (int) (N * (rand()/(RAND_MAX + 1.0)));

Random integer between [ M, N ]

int r = (int) (Μ + (rand()/(RAND_MAX + 0.0))*(N-M+1));

Random integer between [ M, N )

int r = (int) (Μ + (rand()/(RAND_MAX + 1.0))*(N-M+1));

Summary

The general formula is:

int r = (int) (A + (rand()/(RAND_MAX + C))*B);

Values of M, N, K are shown in the following table:

Range A B  C
 [ 0, 1 ]  0  1  0.0
 [ 0, N ]  0  N  0.0
 [ M, N ]  M  N – M + 1  0.0
 [ 0, 1 )  0  1  1.0
 [ 0, N )  0  N  1.0
 [ M, N )  M  N – M + 1  1.0