From dc070b734c0aed0893a610a19b5ad08183353082 Mon Sep 17 00:00:00 2001 From: lighting9999 Date: Sat, 2 May 2026 20:00:23 +0800 Subject: [PATCH 1/3] Add error handling for random() in random.py Handle potential ValueError from random() returning 0.0. --- Lib/random.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Lib/random.py b/Lib/random.py index 86d562f0b8aaf6..9c989ddb76938c 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 From 3c96cf13854712c164bd22241777d39a4f744c28 Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" <43283697+blurb-it[bot]@users.noreply.github.com> Date: Sat, 2 May 2026 12:03:49 +0000 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=93=9C=F0=9F=A4=96=20Added=20by=20blu?= =?UTF-8?q?rb=5Fit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../next/Library/2026-05-02-12-03-48.gh-issue-149221.__KOks.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2026-05-02-12-03-48.gh-issue-149221.__KOks.rst 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`. From e113fe8a06d87beefb3c4cec653bf7eb1282c2bd Mon Sep 17 00:00:00 2001 From: lighting9999 Date: Sat, 2 May 2026 20:09:24 +0800 Subject: [PATCH 3/3] Fix wirtespace --- Lib/random.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Lib/random.py b/Lib/random.py index 9c989ddb76938c..69ab3a96f142db 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -837,9 +837,9 @@ def binomialvariate(self, n=1, p=0.5): return x while True: 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 + 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: