I\'ve written a C function that I think selects integers from a uniform distribution with range [rangeLow, rangeHigh], inclusive. This isn\
A version which corrects the distribution errors (noted by Lior), involves the high-bits returned by rand() and only uses integer math (if that's desirable):
int uniform_distribution(int rangeLow, int rangeHigh)
{
int range = rangeHigh - rangeLow + 1; //+1 makes it [rangeLow, rangeHigh], inclusive.
int copies=RAND_MAX/range; // we can fit n-copies of [0...range-1] into RAND_MAX
// Use rejection sampling to avoid distribution errors
int limit=range*copies;
int myRand=-1;
while( myRand<0 || myRand>=limit){
myRand=rand();
}
return myRand/copies+rangeLow; // note that this involves the high-bits
}
//note: make sure rand() was already initialized using srand()
This should work well provided that range
is much smaller than RAND_MAX
, otherwise
you'll be back to the problem that rand()
isn't a good random number generator in terms of its low-bits.