11.12 Getting a Random Floating-Point Value with Uniform Distribution

11.12.1 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.

11.12.2 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.

11.12.3 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; }


Secure Programming Cookbook for C and C++
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2005
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net