]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-149221:Fix binomialvariate Function for random module (gh-149222)
authorlighting9999 <lightingcloud999@outlook.com>
Sat, 2 May 2026 12:55:43 +0000 (20:55 +0800)
committerGitHub <noreply@github.com>
Sat, 2 May 2026 12:55:43 +0000 (07:55 -0500)
Lib/random.py
Lib/test/test_random.py
Misc/NEWS.d/next/Library/2026-05-02-01-09-29.gh-issue-149221.__KOks.rst [new file with mode: 0644]

index c89cbb755abac869ddb02b8fe9afa50c96dcde4d..dc037629bab0db090f2b64dfbc0b96b8ce1762d7 100644 (file)
@@ -836,7 +836,12 @@ class Random(_random.Random):
             if not c:
                 return x
             while True:
-                y += _floor(_log2(random()) / c) + 1
+                try:
+                    y += _floor(_log2(random()) / c) + 1
+                # The random() function can return 0.0, which causes log2(0.0) to raise a ValueError.
+                # See https://github.com/python/cpython/issue/149221
+                except ValueError:
+                    continue
                 if y > n:
                     return x
                 x += 1
index 1e57b9244b4fd54148d0d2a529ddd0e7bf0e99b8..dbd3b855f536a0d54533981474ca228b0e9c4990 100644 (file)
@@ -1075,6 +1075,12 @@ class TestDistributions(unittest.TestCase):
                                    msg='%s%r' % (variate.__name__, args))
             self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
                                    msg='%s%r' % (variate.__name__, args))
+    def test_binomialvariate_log_zero(self):
+        # gh-149222: Variety random() return 0.0 no input Error
+        with unittest.mock.patch.object(random.Random, 'random', side_effect= [0.0] + [0.5] * 20):
+            result = random.binomialvariate(10, 0.5)
+            self.assertIsInstance(result, int)
+            self.assertIn(result, range(11))
 
     def test_constant(self):
         g = random.Random()
diff --git a/Misc/NEWS.d/next/Library/2026-05-02-01-09-29.gh-issue-149221.__KOks.rst b/Misc/NEWS.d/next/Library/2026-05-02-01-09-29.gh-issue-149221.__KOks.rst
new file mode 100644 (file)
index 0000000..fab2b0f
--- /dev/null
@@ -0,0 +1 @@
+Catch rare math domain error for :func:`random.binomialvariate`.