From 5479f5898840310461a48b1659bf86231b0c9dfb Mon Sep 17 00:00:00 2001 From: Sudhakar Date: Sat, 28 Nov 2026 13:47:50 +0530 Subject: [PATCH] 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. --- Lib/statistics.py | 2 ++ Lib/test/test_statistics.py | 8 ++++++++ .../2026-11-28-12-00-00.gh-issue-162743.Z1xQ9k.rst | 3 +++ 3 files changed, 13 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-11-28-12-00-00.gh-issue-162743.Z1xQ9k.rst diff --git a/Lib/statistics.py b/Lib/statistics.py index aaf3799716d8fb..a16b932ef89f0b 100644 --- a/Lib/statistics.py +++ b/Lib/statistics.py @@ -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] diff --git a/Lib/test/test_statistics.py b/Lib/test/test_statistics.py index 266d92828fe154..83e6cddf21fcbc 100644 --- a/Lib/test/test_statistics.py +++ b/Lib/test/test_statistics.py @@ -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 diff --git a/Misc/NEWS.d/next/Library/2026-11-28-12-00-00.gh-issue-162743.Z1xQ9k.rst b/Misc/NEWS.d/next/Library/2026-11-28-12-00-00.gh-issue-162743.Z1xQ9k.rst new file mode 100644 index 00000000000000..c5823605a3b761 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-28-12-00-00.gh-issue-162743.Z1xQ9k.rst @@ -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.