3 ms·
> and scaling the result to fall within a specified min to max range. This is actually incorrect. Unless the size of the range is a power of two, this gives no
by zAy0LfpBZLC8mAC 10y ago
> and scaling the result to fall within a specified min to max range.
This is actually incorrect. Unless the size of the range is a power of two, this gives non-uniform probability. The bias might be acceptable if it's small enough, but it's something to be aware of, and, if you want to have something robust, to avoid.
A general safe strategy is to check if the raw random value is below the maximum multiple of the size of the range that's no greater than the number of possible values for the raw random value, and if not, generate a new one and repeat. (In principle, any smaller multiple (>= 1) would work as well, but taking the maximum gives the smallest number of retries.)