]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-131435: random.randint optimization (gh-131436)
authordgpb <3577712+dg-pb@users.noreply.github.com>
Thu, 20 Mar 2025 22:07:28 +0000 (00:07 +0200)
committerGitHub <noreply@github.com>
Thu, 20 Mar 2025 22:07:28 +0000 (17:07 -0500)
Lib/random.py
Misc/NEWS.d/next/Library/2025-03-19-20-37-07.gh-issue-131435.y8KMae.rst [new file with mode: 0644]

index 4d9a047b027974fc6318497f1b9c81ce3b2ea7b2..d6f5337d40f6ba120eecda55fd9d18eef5030626 100644 (file)
@@ -336,8 +336,11 @@ class Random(_random.Random):
     def randint(self, a, b):
         """Return random integer in range [a, b], including both end points.
         """
-
-        return self.randrange(a, b+1)
+        a = _index(a)
+        b = _index(b)
+        if b < a:
+            raise ValueError(f"empty range in randint({a}, {b})")
+        return a + self._randbelow(b - a + 1)
 
 
     ## -------------------- sequence methods  -------------------
diff --git a/Misc/NEWS.d/next/Library/2025-03-19-20-37-07.gh-issue-131435.y8KMae.rst b/Misc/NEWS.d/next/Library/2025-03-19-20-37-07.gh-issue-131435.y8KMae.rst
new file mode 100644 (file)
index 0000000..1a9810a
--- /dev/null
@@ -0,0 +1 @@
+10-20% performance improvement of :func:`random.randint`.