https://github.com/python/cpython/commit/4f0cfe53cbb56c32b097f9c38d66444960b5f17f
commit: 4f0cfe53cbb56c32b097f9c38d66444960b5f17f
branch: main
author: lighting9999 <[email protected]>
committer: rhettinger <[email protected]>
date: 2026-05-02T07:55:43-05:00
summary:

gh-149221:Fix binomialvariate Function for random module (gh-149222)

files:
A Misc/NEWS.d/next/Library/2026-05-02-01-09-29.gh-issue-149221.__KOks.rst
M Lib/random.py
M Lib/test/test_random.py

diff --git a/Lib/random.py b/Lib/random.py
index c89cbb755abac8..dc037629bab0db 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -836,7 +836,12 @@ def binomialvariate(self, n=1, p=0.5):
             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
diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py
index 1e57b9244b4fd5..dbd3b855f536a0 100644
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -1075,6 +1075,12 @@ def test_avg_std(self):
                                    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
index 00000000000000..fab2b0f6a23489
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-05-02-01-09-29.gh-issue-149221.__KOks.rst
@@ -0,0 +1 @@
+Catch rare math domain error for :func:`random.binomialvariate`.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to