Here's some code to generate a random number in the range [min,max)
int RandomInRange( const int min, const int max )
{
return ( rand( ) % ( max - min ) ) + min;
}
But... this does not give a nice distribution. If (max - min) is not a divisor of the maximum value that rand( ) can create, then the first N values in the range will have a higher probability of being generated (where N is (rand_max + 1) % (max - min)).
e.g. if rand() generates values from 0-5 (rand_max = 5), and by some chance, it generates the sequence
0,1,2,3,4,5,0,1,2,3,4,5
This is a nice uniform distribution, but putting it through RandomInRange(0,5) gives
0,1,2,3,4,0,0,1,2,3,4,0
, which biases 0. RandomInRange(0,4) gives
0,1,2,3,0,1,0,1,2,3,0,1
which biases 0 and 1.
We can fix RandomInRange() by normalising rand():
float NormalisedRandom( )
{
return float( rand( ) ) / float ( RAND_MAX );
}
int RandomInRange( const int min, const int max )
{
return int( ( NormalisedRandom( ) * float( max - min ) ) + float( min ) );
}
My question is: Is there a faster, non-floating-point way of ensuring a uniform distribution in an arbitrary range?












