Skip to content

Commit 4f0cfe5

Browse files
authored
gh-149221:Fix binomialvariate Function for random module (gh-149222)
1 parent fea2a57 commit 4f0cfe5

3 files changed

Lines changed: 13 additions & 1 deletion

File tree

Lib/random.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -836,7 +836,12 @@ def binomialvariate(self, n=1, p=0.5):
836836
if not c:
837837
return x
838838
while True:
839-
y += _floor(_log2(random()) / c) + 1
839+
try:
840+
y += _floor(_log2(random()) / c) + 1
841+
# The random() function can return 0.0, which causes log2(0.0) to raise a ValueError.
842+
# See https://github.com/python/cpython/issue/149221
843+
except ValueError:
844+
continue
840845
if y > n:
841846
return x
842847
x += 1

Lib/test/test_random.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,6 +1075,12 @@ def test_avg_std(self):
10751075
msg='%s%r' % (variate.__name__, args))
10761076
self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
10771077
msg='%s%r' % (variate.__name__, args))
1078+
def test_binomialvariate_log_zero(self):
1079+
# gh-149222: Variety random() return 0.0 no input Error
1080+
with unittest.mock.patch.object(random.Random, 'random', side_effect= [0.0] + [0.5] * 20):
1081+
result = random.binomialvariate(10, 0.5)
1082+
self.assertIsInstance(result, int)
1083+
self.assertIn(result, range(11))
10781084

10791085
def test_constant(self):
10801086
g = random.Random()
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)