Skip to content

Commit 4441d69

Browse files
gh-163030: Clamp correlation coefficients to range
1 parent 5f6de00 commit 4441d69

2 files changed

Lines changed: 38 additions & 1 deletion

File tree

‎Lib/statistics.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -735,10 +735,18 @@ def correlation(x, y, /, *, method='linear'):
735735
syy = sumprod(y, y)
736736

737737
try:
738-
return sxy / _sqrtprod(sxx, syy)
738+
r = sxy / _sqrtprod(sxx, syy)
739739
except ZeroDivisionError:
740740
raise StatisticsError('at least one of the inputs is constant')
741741

742+
# Rounding can put a finite correlation just outside its mathematical
743+
# range. Use comparisons instead of min/max so that NaN remains NaN.
744+
if r > 1.0:
745+
return 1.0
746+
if r < -1.0:
747+
return -1.0
748+
return r
749+
742750

743751
LinearRegression = namedtuple('LinearRegression', ('slope', 'intercept'))
744752

‎Lib/test/test_statistics.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2831,6 +2831,35 @@ def test_correlation_tiny_inputs(self):
28312831
y = [1e-62, 2e-62, 3e-62]
28322832
self.assertAlmostEqual(statistics.correlation(x, y), 1.0)
28332833

2834+
@requires_IEEE_754
2835+
def test_correlation_rounding_stays_in_range(self):
2836+
# gh-163030: rounding can put a correlation one ulp outside
2837+
# its mathematical range.
2838+
pairs = [
2839+
(
2840+
[-96.58825002910613, -33.41758764126037,
2841+
80.88757048749329, 24.053051499453687],
2842+
[-243.97798201783226, -86.05132604821785,
2843+
199.7115692736663, 57.62527180356729],
2844+
1.0,
2845+
),
2846+
(
2847+
[78.45139891383266, 34.043422148339516,
2848+
77.90250993685783],
2849+
[-33.54753437409516, -11.343545991348583,
2850+
-33.27308988560774],
2851+
-1.0,
2852+
),
2853+
]
2854+
for x, y, expected in pairs:
2855+
with self.subTest(expected=expected):
2856+
self.assertEqual(statistics.correlation(x, y), expected)
2857+
2858+
@requires_IEEE_754
2859+
def test_correlation_preserves_nan(self):
2860+
result = statistics.correlation([1, 2, 3], [math.nan, 2, 3])
2861+
self.assertTrue(math.isnan(result))
2862+
28342863
@requires_IEEE_754
28352864
def test_correlation_asymmetric_scales(self):
28362865
for a, b in [

0 commit comments

Comments
 (0)