Friday, March 18, 2011

Random Numbers

Mike Ash:

Our “random” index is twice as likely to fall within the first half of the array as the second half. As the desired range shrinks, this problem likewise shrinks, but it still exists for any desired range which can’t evenly divide the original range.

The solution to this is to use as much as possible of the original range, and discard the number and try a new one if it falls outside what’s usable.

This is such a common issue that I wonder why there isn’t a solution in the standard library.

Comments RSS · Twitter

Leave a Comment