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`.