logoalt Hacker News

adrian_b • today at 8:48 AM • 0 replies • view on HN

Rejection is unavoidable if you want a uniform distribution for a number of choices that is not a power of two.

Nonetheless, the rejection can be done either before or after the multiplication or division that does most of the job for passing from the input range to the output range.

The place where rejection is done can be chosen to minimize the amount of values that are rejected, making thus unlikely that the branch is taken, so it will be correctly predicted most of the time.

For maximum speed, it is preferable to use multiplication instead of division, i.e. the input is seen as a fraction less than 1 and after multiplication only the integer part is retained. Taking care to use multiplication is normally more important than worrying that rejection may decrease the performance.