Skip to content(if available)orjump to list(if available)

Efficiently Generating a Number in a Range (2018)

eru

Python (or more precisely CPython) uses something like a bitmask and rejection. Alas, there's a bug in the code, so that when you generate a range whose size is a power of two, instead of getting the best case (no rejections), you get half of your values rejected.

For clarity, this worst case for this approach should happen for ranges with size 2*x+1, ie one more than a power of two.

The bug is known but not being fixed right now to keep random number output consistent.