Skip to content
Open
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
2 changes: 2 additions & 0 deletions Lib/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,9 @@ def correlation(x, y, /, *, method='linear'):

else:
xbar = fsum(x) / n
xbar += fsum(xi - xbar for xi in x) / n
ybar = fsum(y) / n
ybar += fsum(yi - ybar for yi in y) / n
x = [xi - xbar for xi in x]
y = [yi - ybar for yi in y]

Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -2850,6 +2850,14 @@ def test_correlation_tiny_products_max_recursion(self):
x = [0.0, 0.0, 0.0, a]
self.assertEqual(statistics.correlation(x, x), 1.0)

def test_correlation_large_timestamp_precision(self):
# gh-162743: mean rounding should not corrupt correlation for
# large timestamp-like values with small differences.
epoch = 1_700_000_000_000_000_000
event = [epoch + offset for offset in (256, 512, 768)]
received = [t + 1024 for t in event]
self.assertEqual(statistics.correlation(event, received), 1.0)

@requires_IEEE_754
@skip_if_double_rounding
@support.cpython_only # Allow for a weaker sumprod() implementation
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:func:`statistics.correlation` now compensates for floating-point
rounding in the mean when centering data, preventing incorrect results
for large values with small differences.
Loading