C Random number generator

Soldato
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
Done a quick search on t'intenet and found what i'm looking for pretty quickly, basically i want a random number between 0 and 16.

The basic idea is that you simply throw away numbers in such a way as to ensure a uniform distribution. For example, if we wanted to generate a number between 0 and 3*RAND_MAX/4, we'd just keep calling rand() until it returned a number in that range. If we want a random number between 0 and 2, we obviously don't want to throw away all numbers greater than or equal to 3 ! Instead, we pick a large (ie close to RAND_MAX) whole number multiple of 3, and throw away all outcomes of rand() greater than or equal to that.

Code:
int_rand(int n)
{
	if ( n <= 0 || n > RAND_MAX )
		throw domain_error("Argument out of range");
	const int bucket_size = RAND_MAX / n;
	int a;
	do 
	{
		a = rand() / bucket_size;
	}
	while ( a >= n );

	return a;
}

Now seeing as n has to be a large number close to that of RAND_MAX and a multiple of 16 (?). The best option for n would appear to be 2047.

So i'm slightly confused how this would work as surely it will keep producing random numbers until a < n i.e. < 2047. So it could be 2046, which is no where near in the range of 0-16
 
Back
Top Bottom