From e4a3e99973caf06c582f98defd24dfb1dd943707 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Wed, 8 Sep 2010 00:30:28 +0000 Subject: In the case where only a user supplied random() method is available, adopt a strategy that makes the fewest calls to random(). --- Lib/random.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Lib/random.py b/Lib/random.py index 0aee06e..62f5905 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -212,33 +212,33 @@ class Random(_random.Random): return self.randrange(a, b+1) - def _randbelow(self, n, int=int, bpf=BPF, type=type, + def _randbelow(self, n, int=int, maxsize=1<= n: r = getrandbits(k) return r # There's an overriden random() method but no new getrandbits() method, # so we can only use random() from here. - if k > bpf: + random = self.random + if n >= maxsize: _warn("Underlying random() generator does not supply \n" "enough bits to choose from a population range this large.\n" "To remove the range limitation, add a getrandbits() method.") - return int(self.random() * n) - random = self.random - N = 1 << k - r = int(N * random()) # 0 <= r < 2**k - while r >= n: - r = int(N * random()) - return r + return int(random() * n) + rem = maxsize % n + limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0 + r = random() + while r >= limit: + r = random() + return int(r*maxsize) % n ## -------------------- sequence methods ------------------- -- cgit v0.12