diff --git a/Lib/statistics.py b/Lib/statistics.py index aaf3799716d8fb..54317b4a735233 100644 --- a/Lib/statistics.py +++ b/Lib/statistics.py @@ -735,10 +735,18 @@ def correlation(x, y, /, *, method='linear'): syy = sumprod(y, y) try: - return sxy / _sqrtprod(sxx, syy) + r = sxy / _sqrtprod(sxx, syy) except ZeroDivisionError: raise StatisticsError('at least one of the inputs is constant') + # Rounding can put a finite correlation just outside its mathematical + # range. Use comparisons instead of min/max so that NaN remains NaN. + if r > 1.0: + return 1.0 + if r < -1.0: + return -1.0 + return r + LinearRegression = namedtuple('LinearRegression', ('slope', 'intercept')) diff --git a/Lib/test/test_statistics.py b/Lib/test/test_statistics.py index 266d92828fe154..1c57793130ef92 100644 --- a/Lib/test/test_statistics.py +++ b/Lib/test/test_statistics.py @@ -2831,6 +2831,35 @@ def test_correlation_tiny_inputs(self): y = [1e-62, 2e-62, 3e-62] self.assertAlmostEqual(statistics.correlation(x, y), 1.0) + @requires_IEEE_754 + def test_correlation_rounding_stays_in_range(self): + # gh-163030: rounding can put a correlation one ulp outside + # its mathematical range. + pairs = [ + ( + [-96.58825002910613, -33.41758764126037, + 80.88757048749329, 24.053051499453687], + [-243.97798201783226, -86.05132604821785, + 199.7115692736663, 57.62527180356729], + 1.0, + ), + ( + [78.45139891383266, 34.043422148339516, + 77.90250993685783], + [-33.54753437409516, -11.343545991348583, + -33.27308988560774], + -1.0, + ), + ] + for x, y, expected in pairs: + with self.subTest(expected=expected): + self.assertEqual(statistics.correlation(x, y), expected) + + @requires_IEEE_754 + def test_correlation_preserves_nan(self): + result = statistics.correlation([1, 2, 3], [math.nan, 2, 3]) + self.assertTrue(math.isnan(result)) + @requires_IEEE_754 def test_correlation_asymmetric_scales(self): for a, b in [ diff --git a/Misc/NEWS.d/next/Library/2026-12-03-11-00-00.gh-issue-163030.rst b/Misc/NEWS.d/next/Library/2026-12-03-11-00-00.gh-issue-163030.rst new file mode 100644 index 00000000000000..2111bedba98ed4 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-03-11-00-00.gh-issue-163030.rst @@ -0,0 +1 @@ +Clamp ``statistics.correlation`` results to the documented range when floating-point rounding puts them just outside it. \ No newline at end of file