From ac6fcb47296d31fc3a0fc2b592b4625a2292b923 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Sat, 25 Nov 2017 12:30:42 +0200 Subject: [PATCH] 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). --- random/random.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/random/random.py b/random/random.py index e69de29b..5a52479a 100644 --- a/random/random.py +++ b/random/random.py @@ -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