diff --git a/Lib/random.py b/Lib/random.py index 86d562f0b8aaf6..76507cea49fd51 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -536,6 +536,8 @@ def triangular(self, low=0.0, high=1.0, mode=None): def normalvariate(self, mu=0.0, sigma=1.0): """Normal distribution. + Conditions on the parameters are sigma > 0. + mu is the mean, and sigma is the standard deviation. """ @@ -544,6 +546,9 @@ def normalvariate(self, mu=0.0, sigma=1.0): # variables using the ratio of uniform deviates", ACM Trans # Math Software, 3, (1977), pp257-260. + if sigma <= 0: + raise ValueError("normalvariate: sigma must be > 0.0") + random = self.random while True: u1 = random() @@ -640,7 +645,9 @@ def vonmisesvariate(self, mu, kappa): random = self.random if kappa <= 1e-6: - return TWOPI * random() + if kappa >= 0: + return TWOPI * random() + raise ValueError("vonmisesvariate: kappa must be >= 0.0") s = 0.5 / kappa r = s + _sqrt(1.0 + s * s) diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index 0217ebd132b110..b0bb0eca3d9f28 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -1084,9 +1084,6 @@ def test_constant(self): (g.expovariate, (float('inf'),), 0.0), (g.vonmisesvariate, (3.0, float('inf')), 3.0), (g.gauss, (10.0, 0.0), 10.0), - (g.lognormvariate, (0.0, 0.0), 1.0), - (g.lognormvariate, (-float('inf'), 0.0), 0.0), - (g.normalvariate, (10.0, 0.0), 10.0), (g.binomialvariate, (0, 0.5), 0), (g.binomialvariate, (10, 0.0), 0), (g.binomialvariate, (10, 1.0), 10), @@ -1152,7 +1149,13 @@ def test_binomialvariate(self): # Demonstrate the BTRS works for huge values of n self.assertTrue(19_000_000 <= B(100_000_000, 0.2) <= 21_000_000) self.assertTrue(89_000_000 <= B(100_000_000, 0.9) <= 91_000_000) + def test_log_norm_errors(self): + # sigma must be > 0.0 + self.assertRaises(ValueError, random.lognormvariate, 1, -2) + def test_von_mises_errors(self): + # kappa must be >= 0.0 + self.assertRaises(ValueError, random.vonmisesvariate, 1, -2) def test_von_mises_range(self): # Issue 17149: von mises variates were not consistently in the