cpython: 1062c66e9bdc (original) (raw)
--- a/Lib/random.py +++ b/Lib/random.py @@ -367,6 +367,16 @@ class Random(_random.Random): http://en.wikipedia.org/wiki/Triangular_distribution[](#l1.4) """
# Sanity check. According to the doc low must be less or equal to[](#l1.7)
# high. And mode should be somewhere between these bounds.[](#l1.8)
if low > high:[](#l1.9)
raise ValueError('high cannot be less then low.')[](#l1.10)
if mode is not None and (mode < low or mode > high):[](#l1.11)
raise ValueError('mode must be between low and high.')[](#l1.12)
if high == low:[](#l1.14)
return low[](#l1.15)
+ u = self.random() c = 0.5 if mode is None else (mode - low) / (high - low) if u > c:
--- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -43,6 +43,33 @@ class TestBasicOps(unittest.TestCase): self.assertRaises(TypeError, self.gen.seed, 1, 2) self.assertRaises(TypeError, type(self.gen), [])
- def test_triangular(self):
# Check that triangular() correctly handles bad input. See issue 13355.[](#l2.8)
# mode > high.[](#l2.9)
with self.assertRaises(ValueError):[](#l2.10)
random.triangular(mode=2)[](#l2.11)
with self.assertRaises(ValueError):[](#l2.12)
random.triangular(low=1, high=10, mode=11)[](#l2.13)
with self.assertRaises(ValueError):[](#l2.14)
random.triangular(low=1, high=1, mode=11)[](#l2.15)
# mode < low.[](#l2.16)
with self.assertRaises(ValueError):[](#l2.17)
random.triangular(mode=-1)[](#l2.18)
with self.assertRaises(ValueError):[](#l2.19)
random.triangular(low=1, high=10, mode=0)[](#l2.20)
with self.assertRaises(ValueError):[](#l2.21)
random.triangular(low=1, high=1, mode=0)[](#l2.22)
# low > high[](#l2.23)
with self.assertRaises(ValueError):[](#l2.24)
random.triangular(low=5, high=2)[](#l2.25)
with self.assertRaises(ValueError):[](#l2.26)
random.triangular(low=5, high=2, mode=1)[](#l2.27)
with self.assertRaises(ValueError):[](#l2.28)
random.triangular(low=-2, high=-5)[](#l2.29)
self.assertEqual(random.triangular(low=10, high=10), 10)[](#l2.31)
self.assertEqual(random.triangular(low=10, high=10, mode=10), 10)[](#l2.32)
+ def test_jumpahead(self): self.gen.seed() state1 = self.gen.getstate() @@ -543,7 +570,7 @@ class TestDistributions(unittest.TestCas for variate, args, expected in [ (g.uniform, (10.0, 10.0), 10.0), (g.triangular, (10.0, 10.0), 10.0),
#(g.triangular, (10.0, 10.0, 10.0), 10.0),[](#l2.41)
(g.triangular, (10.0, 10.0, 10.0), 10.0),[](#l2.42) (g.expovariate, (float('inf'),), 0.0),[](#l2.43) (g.vonmisesvariate, (3.0, float('inf')), 3.0),[](#l2.44) (g.gauss, (10.0, 0.0), 10.0),[](#l2.45)
--- a/Misc/ACKS +++ b/Misc/ACKS @@ -907,6 +907,7 @@ Nick Seidenman Žiga Seilnach Yury Selivanov Fred Sells +Yuriy Senko Jiwon Seo Joakim Sernbrant Roger Serwy
--- a/Misc/NEWS +++ b/Misc/NEWS @@ -22,6 +22,9 @@ Core and Builtins Library ------- +- Issue #13355: Raise ValueError on random.triangular call with invalid params.