Accidental Scientist
 Subscribe to this blog    Add to Technorati Favorites

Thursday, April 03, 2008

Math Puzzle: this one goes to 1.0

Your mission:
You have the following piece of code:

int GetIndex()
{
float rand = GetRandomNumber();
return NUM_ITEMS * rand;
}

... which you'd expect to return a value from 0 to NUM_ITEMS-1, giving a nice equal chance of picking any item from some list at random.

The question is this:

Most random number functions return a value from 0.0 to 0.999999999999999'. (Or, to look at it another way, 1-epsilon, where epsilon is the smallest possible floating point value that can be represented).

However, Joey Badrand (that scandalous cur) has come up with a random number function for your use which returns a value between 0.0 and 1.0! And you have no choice but to use it in your function.

Questions
  1. What does this do to your distribution, and why is it a bad thing?
  2. How do you fix your function so that the output of Joey's random number generator can be used to do the Right Thing?

Labels: , ,