petdance/scratch — Issue #248: Improve random-ness of Parrot_range_rand
Author: petdance
Created: 2011-11-01 04:25:27+00:00
State: open

Parrot_range_rand(min, max, ignored) returns a number between min and max, inclusive.

However, it does so by computing a floating point number, multiplying that be the integer difference, and adding it to the min.

The result of this, in C, is that truncating conversion introduces a bias away from max.

Consider a call `Parrot_range_rand(0, 10, 0)` - the result is min (0 in our case) plus (max-min) (10-0, or 10) times a random number in the range 0.0 ... 1.0.

But because of truncating conversion, 10*(rand) will convert to 0 about 10% of the time (0.000 ... 0.099), 1 about 10% of the time (0.100 ... 0.199), ..., and 9 about 10% of the time (0.900 ... 0.999). About 0% of the time (there is a change of hitting 1.0, but floats have a ''lot'' of decimal places...) the result will be 10.