[pypy-commit] pypy py3k: Fix _random.get_randbits()

amauryfa noreply at buildbot.pypy.org
Fri Nov 11 21:50:29 CET 2011


Author: Amaury Forgeot d'Arc <amauryfa at gmail.com>
Branch: py3k
Changeset: r49347:7ea6a7e448e0
Date: 2011-11-11 21:48 +0100
http://bitbucket.org/pypy/pypy/changeset/7ea6a7e448e0/

Log:	Fix _random.get_randbits()

diff --git a/pypy/module/_random/interp_random.py b/pypy/module/_random/interp_random.py
--- a/pypy/module/_random/interp_random.py
+++ b/pypy/module/_random/interp_random.py
@@ -91,11 +91,11 @@
             raise OperationError(space.w_ValueError, strerror)
         needed = (k - 1) // rbigint.SHIFT + 1
         result = rbigint.rbigint([rbigint.NULLDIGIT] * needed, 1)
-        for i in range(needed - 1):
-            # This loses some random digits, but not too many since SHIFT=31
-            value = self._rnd.genrand32()
+        for i in range(needed):
+            # This wastes some random digits, but not too many since SHIFT=31
+            value = self._rnd.genrand32() & rbigint.MASK
             if i < needed - 1:
-                result.setdigit(i, value & rbigint.MASK)
+                result.setdigit(i, value)
             else:
                 result.setdigit(i, value >> ((needed * rbigint.SHIFT) - k))
         return space.newlong_from_rbigint(result)
diff --git a/pypy/module/_random/test/test_random.py b/pypy/module/_random/test/test_random.py
--- a/pypy/module/_random/test/test_random.py
+++ b/pypy/module/_random/test/test_random.py
@@ -98,6 +98,7 @@
         for n in range(10, 1000, 15):
             k = rnd.getrandbits(n)
             assert 0 <= k < 2 ** n
+        assert rnd.getrandbits(30) != 0 # Fails every 1e10 runs
 
     def test_subclass(self):
         import _random


More information about the pypy-commit mailing list