Skip to content

Commit 5479f58

Browse files
committed
gh-162743: Fix correlation mean rounding for large timestamps
Compensate the mean in statistics.correlation() so floating-point rounding in fsum/n does not corrupt centered data when inputs are large with small differences.
1 parent 49a344e commit 5479f58

3 files changed

Lines changed: 13 additions & 0 deletions

File tree

‎Lib/statistics.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -726,7 +726,9 @@ def correlation(x, y, /, *, method='linear'):
726726

727727
else:
728728
xbar = fsum(x) / n
729+
xbar += fsum(xi - xbar for xi in x) / n
729730
ybar = fsum(y) / n
731+
ybar += fsum(yi - ybar for yi in y) / n
730732
x = [xi - xbar for xi in x]
731733
y = [yi - ybar for yi in y]
732734

‎Lib/test/test_statistics.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2850,6 +2850,14 @@ def test_correlation_tiny_products_max_recursion(self):
28502850
x = [0.0, 0.0, 0.0, a]
28512851
self.assertEqual(statistics.correlation(x, x), 1.0)
28522852

2853+
def test_correlation_large_timestamp_precision(self):
2854+
# gh-162743: mean rounding should not corrupt correlation for
2855+
# large timestamp-like values with small differences.
2856+
epoch = 1_700_000_000_000_000_000
2857+
event = [epoch + offset for offset in (256, 512, 768)]
2858+
received = [t + 1024 for t in event]
2859+
self.assertEqual(statistics.correlation(event, received), 1.0)
2860+
28532861
@requires_IEEE_754
28542862
@skip_if_double_rounding
28552863
@support.cpython_only # Allow for a weaker sumprod() implementation
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:func:`statistics.correlation` now compensates for floating-point
2+
rounding in the mean when centering data, preventing incorrect results
3+
for large values with small differences.

0 commit comments

Comments
 (0)