Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -836,7 +836,11 @@ 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
except ValueError:
# Reject case where random() returned 0.0
continue
Comment on lines +839 to +843

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Limit suppression to the zero draw

When a Random subclass's random() raises ValueError (for example, because its entropy source fails), this handler catches that exception as though the method returned zero and retries forever instead of propagating the failure. It also loops on invalid negative or NaN return values. Call random() outside the try and explicitly retry only when the returned value is 0.0, so unrelated errors retain their previous behavior.

Useful? React with 👍 / 👎.

if y > n:
return x
x += 1
Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -1154,6 +1154,17 @@ def test_binomialvariate(self):
self.assertTrue(89_000_000 <= B(100_000_000, 0.9) <= 91_000_000)


@unittest.mock.patch('random.Random.random')
def test_binomialvariate_zero_random(self, random_mock):
# gh-149221: random() can legitimately return 0.0 (its documented
# range is [0.0, 1.0)). The BG geometric branch must reject that
# draw instead of raising "math domain error" from log2(0.0).
seq = iter([0.0])
random_mock.side_effect = lambda: next(seq, 0.5)
# n*p == 2.0 < 10.0 selects the BG geometric method.
self.assertIn(random.binomialvariate(20, 0.1), range(21))


def test_von_mises_range(self):
# Issue 17149: von mises variates were not consistently in the
# range [0, 2*PI].
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:meth:`random.Random.binomialvariate` no longer raises :exc:`ValueError`
when the underlying :meth:`~random.Random.random` returns ``0.0`` while sampling
with ``n * p < 10``.
Loading