[issue23974] random.randrange() biased output

Christopher Gurnee report at bugs.python.org
Thu Apr 16 21:40:54 CEST 2015


Christopher Gurnee added the comment:

I shouldn't have called this a rounding error issue, that's not really what it is.

A smaller example might help.

If I'm given a random int, x, in the range [0, 12), and asked to produce from it a random int, y, in the range (0,8], I've got (at least?) two choices:

1. y = x If x < 8 Else fail
2. y = f(x), where f maps values from [0, 12) -> (0,8]

The problem with method 2 is you end up with a mapping like this:
0,1  -> 0
2    -> 1
3,4  -> 2
5    -> 3
6,7  -> 4
8    -> 5
9,10 -> 6
11   -> 7

_randbelow() uses method 1 above. _int(self.random() * istart) is more like method 2.

I chose 2^53 * 2/3 just because the bias was easy to demonstrate. There will always be some bias when stop-start % 2^53 != 0, but it might not manifest itself as easily as checking for evenness.

Personally, I think 2^52 is still way too high as a cutoff point for using the (presumably faster, I didn't timeit) method 2, but I don't claim to be an expert here....

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23974>
_______________________________________


More information about the Python-bugs-list mailing list