21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Solution<br />

Because of the way that floating-point numbers are stored, simply casting bits to a<br />

float will make the distribution nonuniform. Instead, get a random unsigned integer,<br />

and divide.<br />

Discussion<br />

Because integer values are uniformly distributed, you can get a random integer and<br />

divide so that it is a value between 0 and 1:<br />

#include <br />

double spc_rand_real(void) {<br />

return ((double)spc_rand_uint( )) / (double)UINT_MAX;<br />

}<br />

Note that to get a random number between 0 and n, you can multiply the result of<br />

spc_rand_real( ) by n. To get a real number within a range inclusive of the range’s<br />

bounds, do this:<br />

#include <br />

double spc_rand_real_range(double min, double max) {<br />

if (max < min) abort( );<br />

return spc_rand_real( ) * (max - min) + min;<br />

}<br />

11.13 Getting Floating-Point Values with<br />

Nonuniform Distributions<br />

<strong>Problem</strong><br />

You want to select random real numbers in a nonuniform distribution.<br />

Solution<br />

The exact solution varies depending on the distribution. We provide implementations<br />

for many common distributions in this recipe.<br />

Discussion<br />

Do not worry if you do not know what a particular distribution is; if you have never<br />

seen it before, you really should not need to know what it is. A uniform distribution<br />

(as discussed in Recipe 11.12) is far more useful in most cases.<br />

Getting Floating-Point Values with Nonuniform Distributions | 609<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!