8000 gh-135647 fix random.vonmisesvariate() and random.lognormvariate() ac… · python/cpython@70f524f · GitHub
[go: up one dir, main page]

Skip to content
10000

Commit 70f524f

Browse files
gh-135647 fix random.vonmisesvariate() and random.lognormvariate() accept invalid parameters
1 parent 0243260 commit 70f524f

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

Lib/random.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,8 @@ def triangular(self, low=0.0, high=1.0, mode=None):
536536
def normalvariate(self, mu=0.0, sigma=1.0):
537537
"""Normal distribution.
538538
539+
Conditions on the parameters are sigma > 0.
540+
539541
mu is the mean, and sigma is the standard deviation.
540542
541543
"""
@@ -544,6 +546,9 @@ def normalvariate(self, mu=0.0, sigma=1.0):
544546
# variables using the ratio of uniform deviates", ACM Trans
545547
# Math Software, 3, (1977), pp257-260.
546548

549+
if sigma <= 0:
550+
raise ValueError("normalvariate: sigma must be > 0.0")
551+
547552
random = self.random
548553
while True:
549554
u1 = random()
@@ -640,7 +645,9 @@ def vonmisesvariate(self, mu, kappa):
640645

641646
random = self.random
642647
if kappa <= 1e-6:
643-
return TWOPI * random()
648+
if kappa >= 0:
649+
return TWOPI * random()
650+
raise ValueError("vonmisesvariate: kappa must be >= 0.0")
644651

645652
s = 0.5 / kappa
646653
r = s + _sqrt(1.0 + s * s)

Lib/test/test_random.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,9 +1084,6 @@ def test_constant(self):
10841084
(g.expovariate, (float('inf'),), 0.0),
10851085
(g.vonmisesvariate, (3.0, float('inf')), 3.0),
10861086
(g.gauss, (10.0, 0.0), 10.0),
1087-
(g.lognormvariate, (0.0, 0.0), 1.0),
1088-
(g.lognormvariate, (-float('inf'), 0.0), 0.0),
1089-
(g.normalvariate, (10.0, 0.0), 10.0),
10901087
(g.binomialvariate, (0, 0.5), 0),
10911088
(g.binomialvariate, (10, 0.0), 0),
10921089
(g.binomialvariate, (10, 1.0), 10),
@@ -1152,7 +1149,14 @@ def test_binomialvariate(self):
11521149
# Demonstrate the BTRS works for huge values of n
11531150
self.assertTrue(19_000_000 <= B(100_000_000, 0.2) <= 21_000_000)
11541151
self.assertTrue(89_000_000 <= B(100_000_000, 0.9) <= 91_000_000)
1155-
1152+
1153+
def test_log_norm_errors(self):
1154+
# sigma must be > 0.0
1155+
self.assertRaises(ValueError, random.lognormvariate, 1, -2)
1156+
1157+
def test_von_mises_errors(self):
1158+
# kappa must be >= 0.0
1159+
self.assertRaises(ValueError, random.vonmisesvariate, 1, -2)
11561160

11571161
def test_von_mises_range(self):
11581162
# Issue 17149: von mises variates were not consistently in the

0 commit comments

Comments
 (0)
0