How do I scale down numbers from rand()?

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.


int rawRand = rand() % 101;

See (for more details):

rand - C++ Reference

Others have also pointed out that this is not going to give you the best distribution of random numbers possible. If that kind of thing is important in your code, you would have to do:

int rawRand = (rand() * 1.0 / RAND_MAX) * 100;

EDIT

Three years on, I'm making an edit. As others mentioned, rand() has a great deal of issues. Obviously, I can't recommend its use when there are better alternatives going forward. You can read all about the details and recommendations here:

rand() Considered Harmful | GoingNative 2013


If you are using C++ and are concerned about good distribution you can use TR1 C++11 <random>.

#include <random>

std::random_device rseed;
std::mt19937 rgen(rseed()); // mersenne_twister
std::uniform_int_distribution<int> idist(0,100); // [0,100]

std::cout << idist(rgen) << std::endl;