Skip to content
Merged
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 @@ -828,7 +828,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:
Comment thread
StanFromIreland marked this conversation as resolved.
# Reject case where random() returned 0.0
continue
if y > n:
return x
x += 1
Expand Down
7 changes: 7 additions & 0 deletions Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -1101,6 +1101,13 @@ def test_avg_std(self):
self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
msg='%s%r' % (variate.__name__, args))

def test_binomialvariate_log_zero(self):
# gh-149222: Variety random() return 0.0 no input Error
with unittest.mock.patch.object(random.Random, 'random', side_effect=[0.0] + [0.5] * 20):
result = random.binomialvariate(10, 0.5)
self.assertIsInstance(result, int)
self.assertIn(result, range(11))

def test_binomialvariate_btrs_random_zero(self):
for p, expected in ((0.25, 25), (0.75, 75)):
with self.subTest(p=p):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Catch rare math domain error for :func:`random.binomialvariate`.
Loading