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 @@ -849,7 +849,11 @@ def binomialvariate(self, n=1, p=0.5):
u = random()
u -= 0.5
us = 0.5 - _fabs(u)
k = _floor((2.0 * a / us + b) * u + c)
try:
k = _floor((2.0 * a / us + b) * u + c)
except ZeroDivisionError:
# Reject case where random() returned 0.0
continue
if k < 0 or k > n:
continue

Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -1101,6 +1101,14 @@ def test_avg_std(self):
self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
msg='%s%r' % (variate.__name__, args))

def test_binomialvariate_btrs_random_zero(self):
for p, expected in ((0.25, 25), (0.75, 75)):
with self.subTest(p=p):
g = random.Random()
with unittest.mock.patch.object(
g, 'random', side_effect=(0.0, 0.5, 0.5)):
self.assertEqual(g.binomialvariate(100, p), expected)

def test_constant(self):
g = random.Random()
N = 100
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :func:`random.binomialvariate` raising :exc:`ZeroDivisionError`
when :func:`random.random` returns zero.
Loading