Skip to content

Commit 64bccca

Browse files
miss-islingtonlkk7
andauthored
[3.14] gh-154001: Avoid division by zero in binomialvariate (GH-154004) (GH-154051)
(cherry picked from commit 1f13740) Co-authored-by: Łukasz <lukaszlapinski7@gmail.com>
1 parent 6f198d2 commit 64bccca

3 files changed

Lines changed: 15 additions & 1 deletion

File tree

Lib/random.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -861,7 +861,11 @@ def binomialvariate(self, n=1, p=0.5):
861861
u = random()
862862
u -= 0.5
863863
us = 0.5 - _fabs(u)
864-
k = _floor((2.0 * a / us + b) * u + c)
864+
try:
865+
k = _floor((2.0 * a / us + b) * u + c)
866+
except ZeroDivisionError:
867+
# Reject case where random() returned 0.0
868+
continue
865869
if k < 0 or k > n:
866870
continue
867871
v = random()

Lib/test/test_random.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1074,6 +1074,14 @@ def test_avg_std(self):
10741074
self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
10751075
msg='%s%r' % (variate.__name__, args))
10761076

1077+
def test_binomialvariate_btrs_random_zero(self):
1078+
for p, expected in ((0.25, 25), (0.75, 75)):
1079+
with self.subTest(p=p):
1080+
g = random.Random()
1081+
with unittest.mock.patch.object(
1082+
g, 'random', side_effect=(0.0, 0.5, 0.5)):
1083+
self.assertEqual(g.binomialvariate(100, p), expected)
1084+
10771085
def test_constant(self):
10781086
g = random.Random()
10791087
N = 100
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :func:`random.binomialvariate` raising :exc:`ZeroDivisionError`
2+
when :func:`random.random` returns zero.

0 commit comments

Comments
 (0)