11.12. Getting a Random Floating-Point Value with Uniform Distribution
Problem
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.
Solution
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.
Discussion
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; }
Get Secure Programming Cookbook for C and C++ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.