https://github.com/python/cpython/commit/a6d7bf53c8037c7b09b66937f1f8dc781e46099b
commit: a6d7bf53c8037c7b09b66937f1f8dc781e46099b
branch: 3.14
author: lighting9999 <[email protected]>
committer: rhettinger <[email protected]>
date: 2026-05-02T07:57:42-05:00
summary:

[3.14]gh-149221:Fix binomialvariate Function for random module (gh-149276)

files:
A Misc/NEWS.d/next/Library/2026-05-02-12-03-48.gh-issue-149221.__KOks.rst
M Lib/random.py

diff --git a/Lib/random.py b/Lib/random.py
index 86d562f0b8aaf6..69ab3a96f142db 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/Misc/NEWS.d/next/Library/2026-05-02-12-03-48.gh-issue-149221.__KOks.rst 
b/Misc/NEWS.d/next/Library/2026-05-02-12-03-48.gh-issue-149221.__KOks.rst
new file mode 100644
index 00000000000000..fab2b0f6a23489
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-05-02-12-03-48.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