Skip to content

Commit b51a036

Browse files
miss-islingtonlkk7
andauthored
[3.13] gh-154001: Avoid division by zero in binomialvariate (GH-154004) (GH-154052)
(cherry picked from commit 1f13740) Co-authored-by: Łukasz <lukaszlapinski7@gmail.com>
1 parent 6006264 commit b51a036

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

Lib/test/test_random.py

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

1104+
def test_binomialvariate_btrs_random_zero(self):
1105+
for p, expected in ((0.25, 25), (0.75, 75)):
1106+
with self.subTest(p=p):
1107+
g = random.Random()
1108+
with unittest.mock.patch.object(
1109+
g, 'random', side_effect=(0.0, 0.5, 0.5)):
1110+
self.assertEqual(g.binomialvariate(100, p), expected)
1111+
11041112
def test_constant(self):
11051113
g = random.Random()
11061114
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)