July 2003
Intermediate to advanced
790 pages
23h 35m
English
When looking for a random floating-point number, we usually want a value between 0 and 1 that is just as likely to be between 0 and 0.1 as it is to be between 0.9 and 1.
Because of the way that floating-point numbers are stored, simply casting bits to a float will make the distribution nonuniform. Instead, get a random unsigned integer, and divide.
Because integer values are uniformly distributed, you can get a random integer and divide so that it is a value between 0 and 1:
#include <limits.h>
double spc_rand_real(void) {
return ((double)spc_rand_uint( )) / (double)UINT_MAX;
}Note that to get a random number between 0 and
n, you can multiply the result of
spc_rand_real( )
by n. To get a real
number within a range inclusive of the range’s
bounds, do this:
#include <stdlib.h>
double spc_rand_real_range(double min, double max) {
if (max < min) abort( );
return spc_rand_real( ) * (max - min) + min;
}Read now
Unlock full access