From a6d7bf53c8037c7b09b66937f1f8dc781e46099b Mon Sep 17 00:00:00 2001 From: lighting9999 Date: Sat, 2 May 2026 20:57:42 +0800 Subject: [PATCH] [3.14]gh-149221:Fix binomialvariate Function for random module (gh-149276) --- Lib/random.py | 7 ++++++- .../Library/2026-05-02-12-03-48.gh-issue-149221.__KOks.rst | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-05-02-12-03-48.gh-issue-149221.__KOks.rst diff --git a/Lib/random.py b/Lib/random.py index 86d562f0b8aa..69ab3a96f142 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -836,7 +836,12 @@ class Random(_random.Random): 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 000000000000..fab2b0f6a234 --- /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`. -- 2.47.3