From 734d2ade77ad2ea11e7218cfbaa49245bee332b2 Mon Sep 17 00:00:00 2001 From: lighting9999 Date: Sat, 2 May 2026 21:44:06 +0800 Subject: [PATCH 1/3] [3.13]gh-149221:Fix binomialvariate Function for random module Handle ValueError from random() in log2 calculation. --- Lib/random.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Lib/random.py b/Lib/random.py index 1abcae77c8be57..8f0a9f0503f250 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -828,7 +828,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 4168e26684266c81284a5da9d17b5605d6c3c602 Mon Sep 17 00:00:00 2001 From: lighting9999 Date: Sat, 2 May 2026 21:53:08 +0800 Subject: [PATCH 2/3] Simplify ValueError handling in random function Refactor exception handling for ValueError in random.py --- Lib/random.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Lib/random.py b/Lib/random.py index 8f0a9f0503f250..778c54c718677f 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -830,10 +830,8 @@ def binomialvariate(self, n=1, p=0.5): 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 - except ValueError: - continue + except ValueError: + continue if y > n: return x x += 1 From 8feb45acb5fc1ee814c3017e6ccb334988f9a417 Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" <43283697+blurb-it[bot]@users.noreply.github.com> Date: Sat, 2 May 2026 13:54:20 +0000 Subject: [PATCH 3/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-13-54-19.gh-issue-149221.__KOks.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2026-05-02-13-54-19.gh-issue-149221.__KOks.rst diff --git a/Misc/NEWS.d/next/Library/2026-05-02-13-54-19.gh-issue-149221.__KOks.rst b/Misc/NEWS.d/next/Library/2026-05-02-13-54-19.gh-issue-149221.__KOks.rst new file mode 100644 index 00000000000000..fab2b0f6a23489 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-05-02-13-54-19.gh-issue-149221.__KOks.rst @@ -0,0 +1 @@ +Catch rare math domain error for :func:`random.binomialvariate`.