In addition to the other excellent solutions offered here, you can also increase the power in RAND_MAX, truncate with the help of the user MY_RAND_MAX, and discard solutions that could lead to disruption of uniformity.
int myrand(int MY_RAND_MAX) { int j = 0, num = 0; // Generate digits for expansion in powers of RAND_MAX, up to acceptable range. while (pow(RAND_MAX + 1, j) <= MY_RAND_MAX){ num = num + rand() * (int)pow(RAND_MAX + 1, j); j++; } //compute remainder to determine truncation int remainder = ((int)pow(RAND_MAX + 1, j)) % (MY_RAND_MAX + 1); // If number is within accepted bounds, mod and return if (num <= ( (int)pow(RAND_MAX + 1, j) - remainder ) ){ return (num % (MY_RAND_MAX + 1)); // Else, if number generated exceeds allowed bounds, rerun method. }else if (num > ( (int)pow(RAND_MAX + 1, j) - remainder ) ){ return myrand(MY_RAND_MAX); }else{ exit(-1); } }
You can empirically verify that this method gives you a statistically uniform output in a given range.
I did this for several tests with different ranges, each with a sample size of 100,000, and I got agreement between the sample variance and the expected variance of at least 3 sig. everytime.
ps I'm not a coder, but a mathematician / physicist who recently learned to code, so any feedback on the quality of my code will be appreciated.
source share