https://github.com/python/cpython/commit/15335ae20f1f214a36148d31475a1de61614d4d6
commit: 15335ae20f1f214a36148d31475a1de61614d4d6
branch: 3.15
author: Miss Islington (bot) <[email protected]>
committer: serhiy-storchaka <[email protected]>
date: 2026-07-19T09:28:18Z
summary:

[3.15] gh-154001: Avoid division by zero in binomialvariate (GH-154004) 
(GH-154050)

(cherry picked from commit 1f1374009b681814642ca199136815b223fd90ae)

Co-authored-by: Ɓukasz <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-07-18-17-09-49.gh-issue-154001.3brrUv.rst
M Lib/random.py
M Lib/test/test_random.py

diff --git a/Lib/random.py b/Lib/random.py
index 4541267bab866a..7db761034509d3 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -861,7 +861,11 @@ def binomialvariate(self, n=1, p=0.5):
             u = random()
             u -= 0.5
             us = 0.5 - _fabs(u)
-            k = _floor((2.0 * a / us + b) * u + c)
+            try:
+                k = _floor((2.0 * a / us + b) * u + c)
+            except ZeroDivisionError:
+                # Reject case where random() returned 0.0
+                continue
             if k < 0 or k > n:
                 continue
             v = random()
diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py
index dbd3b855f536a0..8d093ab1b7014a 100644
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -1082,6 +1082,14 @@ def test_binomialvariate_log_zero(self):
             self.assertIsInstance(result, int)
             self.assertIn(result, range(11))
 
+    def test_binomialvariate_btrs_random_zero(self):
+        for p, expected in ((0.25, 25), (0.75, 75)):
+            with self.subTest(p=p):
+                g = random.Random()
+                with unittest.mock.patch.object(
+                        g, 'random', side_effect=(0.0, 0.5, 0.5)):
+                    self.assertEqual(g.binomialvariate(100, p), expected)
+
     def test_constant(self):
         g = random.Random()
         N = 100
diff --git 
a/Misc/NEWS.d/next/Library/2026-07-18-17-09-49.gh-issue-154001.3brrUv.rst 
b/Misc/NEWS.d/next/Library/2026-07-18-17-09-49.gh-issue-154001.3brrUv.rst
new file mode 100644
index 00000000000000..ff019aa3618847
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-18-17-09-49.gh-issue-154001.3brrUv.rst
@@ -0,0 +1,2 @@
+Fix :func:`random.binomialvariate` raising :exc:`ZeroDivisionError`
+when :func:`random.random` returns zero.

_______________________________________________
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