Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Lib/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'))

Expand Down
29 changes: 29 additions & 0 deletions Lib/test/test_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use @support.subTests

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 [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Clamp ``statistics.correlation`` results to the documented range when floating-point rounding puts them just outside it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use a backref to statistics.correlation.

Loading