diff --git a/Lib/random.py b/Lib/random.py index 6388f299d37..c2750719ac7 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -449,9 +449,9 @@ class Random(_random.Random): u3 = random() if u3 > 0.5: - theta = (mu % TWOPI) + _acos(f) + theta = (mu + _acos(f)) % TWOPI else: - theta = (mu % TWOPI) - _acos(f) + theta = (mu - _acos(f)) % TWOPI return theta diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index b5931baf4ef..b176ea1dd09 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -479,6 +479,20 @@ class TestDistributions(unittest.TestCase): self.assertAlmostEqual(s1/N, mu, places=2) self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2) + def test_von_mises_range(self): + # Issue 17149: von mises variates were not consistently in the + # range [0, 2*PI]. + g = random.Random() + N = 100 + for mu in 0.0, 0.1, 3.1, 6.2: + for kappa in 0.0, 2.3, 500.0: + for _ in range(N): + sample = g.vonmisesvariate(mu, kappa) + self.assertTrue( + 0 <= sample <= random.TWOPI, + msg=("vonmisesvariate({}, {}) produced a result {} out" + " of range [0, 2*pi]").format(mu, kappa, sample)) + class TestModule(unittest.TestCase): def testMagicConstants(self): self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141) diff --git a/Misc/NEWS b/Misc/NEWS index 730eab173d7..cf6ef47c8e4 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -172,6 +172,9 @@ Core and Builtins Library ------- +- Issue #17149: Fix random.vonmisesvariate to always return results in + [0, 2*math.pi]. + - Issue #1470548: XMLGenerator now works with binary output streams. - Issue #6975: os.path.realpath() now correctly resolves multiple nested