From d5786f2b0d8b07248b966803da89a1fafac778a5 Mon Sep 17 00:00:00 2001 From: "d.grigonis" Date: Wed, 9 Apr 2025 17:42:03 +0300 Subject: [PATCH 1/2] init --- Lib/random.py | 2 +- Lib/test/test_random.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/random.py b/Lib/random.py index 5e5d0c4c694a1c..83258942163978 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -245,7 +245,7 @@ def __init_subclass__(cls, /, **kwargs): def _randbelow_with_getrandbits(self, n): "Return a random int in the range [0,n). Defined for n > 0." - k = n.bit_length() + k = (n - 1).bit_length() r = self.getrandbits(k) # 0 <= r < 2**k while r >= n: r = self.getrandbits(k) diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index 96f6cc86219a5d..f963f5a040c4a3 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -813,7 +813,7 @@ def test_randrange_uses_getrandbits(self): self.gen.seed(1234567) # If randrange uses getrandbits, it should pick getrandbits(100) # when called with a 100-bits stop argument. - self.assertEqual(self.gen.randrange(2**99), + self.assertEqual(self.gen.randrange(2**99 + 1), 97904845777343510404718956115) def test_randbelow_logic(self, _log=log, int=int): From a66f01224f9b68598b3eddb8809043c26233b6c3 Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" <43283697+blurb-it[bot]@users.noreply.github.com> Date: Wed, 9 Apr 2025 14:59:55 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=9C=F0=9F=A4=96=20Added=20by=20blu?= =?UTF-8?q?rb=5Fit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../next/Library/2025-04-09-14-59-52.gh-issue-132320.qa1OoM.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2025-04-09-14-59-52.gh-issue-132320.qa1OoM.rst diff --git a/Misc/NEWS.d/next/Library/2025-04-09-14-59-52.gh-issue-132320.qa1OoM.rst b/Misc/NEWS.d/next/Library/2025-04-09-14-59-52.gh-issue-132320.qa1OoM.rst new file mode 100644 index 00000000000000..b1b52ae978baff --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-04-09-14-59-52.gh-issue-132320.qa1OoM.rst @@ -0,0 +1 @@ +20-30% performance improvement when generating integers lower than some power of 2. E.g. :func:`!random.randint(0, 2**32-1)`