Skip to content

Commit d475f4d

Browse files
lighting9999blurb-it[bot]hugovk
authored
[3.13] gh-149221:Fix binomialvariate Function for random module (#149279)
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com> Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
1 parent 2af2564 commit d475f4d

3 files changed

Lines changed: 13 additions & 1 deletion

File tree

Lib/random.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -828,7 +828,11 @@ def binomialvariate(self, n=1, p=0.5):
828828
if not c:
829829
return x
830830
while True:
831-
y += _floor(_log2(random()) / c) + 1
831+
try:
832+
y += _floor(_log2(random()) / c) + 1
833+
except ValueError:
834+
# Reject case where random() returned 0.0
835+
continue
832836
if y > n:
833837
return x
834838
x += 1

Lib/test/test_random.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1101,6 +1101,13 @@ 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_log_zero(self):
1105+
# gh-149222: Variety random() return 0.0 no input Error
1106+
with unittest.mock.patch.object(random.Random, 'random', side_effect=[0.0] + [0.5] * 20):
1107+
result = random.binomialvariate(10, 0.5)
1108+
self.assertIsInstance(result, int)
1109+
self.assertIn(result, range(11))
1110+
11041111
def test_binomialvariate_btrs_random_zero(self):
11051112
for p, expected in ((0.25, 25), (0.75, 75)):
11061113
with self.subTest(p=p):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Catch rare math domain error for :func:`random.binomialvariate`.

0 commit comments

Comments
 (0)