21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

You might worry about a situation where performance suffers because this code has<br />

to retry too many times. The worst case for this solution is when the size of the range<br />

is UINT_MAX / 2 + 1. Even in such a case, you would not expect to call spc_rand_<br />

uint( ) very many times. The average number of times it would be called here would<br />

be slightly less than two. While the worst-case performance is theoretically<br />

unbounded, the chances of calling spc_rand_uint( ) more than a dozen times are<br />

essentially zero. Therefore, this technique will not have a significant performance<br />

impact for most applications.<br />

If you are okay with some items being slightly more likely than others, there are two<br />

different things you can do, both of which are fairly easy. First, you can perform a<br />

modulo operation and an addition to get the integer in the right range, and just not<br />

worry about the fact that some values are more likely than others:<br />

#include <br />

int spc_rand_range(int min, int max) {<br />

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

return min + (spc_rand_uint( ) % (max - min + 1));<br />

}<br />

Of course, this solution clumps together all the values that are more likely to be chosen,<br />

which is somewhat undesirable. As an alternative, you can spread them out by<br />

using division and rounding down, instead of a simple modulus:<br />

#include <br />

int spc_rand_range(int min, int max) {<br />

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

return min + (int)((double)spc_rand_uint( ) *<br />

(max - min + 1) / (double)UINT_MAX) % (max - min);<br />

}<br />

Note the modulo operation in this solution. That is to prevent getting a value that is<br />

out of range in the very rare occasion that spc_rand_uint( ) returns UINT_MAX.<br />

See Also<br />

Recipe 11.10<br />

11.12 Getting a Random Floating-Point Value<br />

with Uniform Distribution<br />

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

When looking for a random floating-point number, we usually want a value between<br />

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.<br />

608 | Chapter 11: Random Numbers<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!