random: Add randrange() implementation.

The idea behind this implementation is that getrandbits() is guaranteed
(required) to be equally distributed. Thus, we can just repeatedly
sample it until get a suitable value, there's no bias accumulated and
the process should be finite (and on average take few iterations).
pull/226/merge
Paul Sokolovsky 2017-11-25 12:30:42 +02:00
rodzic 693b229f8d
commit ac6fcb4729
1 zmienionych plików z 18 dodań i 0 usunięć

Wyświetl plik

@ -0,0 +1,18 @@
from urandom import *
def randrange(start, stop=None):
if stop is None:
stop = start
start = 0
upper = stop - start
bits = 0
pwr2 = 1
while upper > pwr2:
pwr2 <<= 1
bits += 1
while True:
r = getrandbits(bits)
if r < upper:
break
return r + start