diff --git a/Lib/statistics.py b/Lib/statistics.py index aaf3799716d8fb..e7ca5c293fbd74 100644 --- a/Lib/statistics.py +++ b/Lib/statistics.py @@ -656,6 +656,23 @@ def pstdev(data, mu=None): ## Statistics for relations between two inputs ############################# +def _center(data, n): + """Return ``data`` minus its mean, keeping precision for large offsets. + + Subtracting a large common offset first keeps the deviations exact + instead of losing them when the mean itself is rounded. + """ + origin = next(iter(data)) + shifted = [value - origin for value in data] + if all(isfinite(value) for value in shifted): + mean = fsum(value / n for value in shifted) + centered = [value - mean for value in shifted] + if all(isfinite(value) for value in centered): + return centered + mean = fsum(data) / n + return [value - mean for value in data] + + def covariance(x, y, /): """Covariance @@ -679,9 +696,9 @@ def covariance(x, y, /): raise StatisticsError('covariance requires that both inputs have same number of data points') if n < 2: raise StatisticsError('covariance requires at least two data points') - xbar = fsum(x) / n - ybar = fsum(y) / n - sxy = sumprod((xi - xbar for xi in x), (yi - ybar for yi in y)) + x = _center(x, n) + y = _center(y, n) + sxy = sumprod(x, y) return sxy / (n - 1) @@ -725,10 +742,8 @@ def correlation(x, y, /, *, method='linear'): y = _rank(y, start=start) else: - xbar = fsum(x) / n - ybar = fsum(y) / n - x = [xi - xbar for xi in x] - y = [yi - ybar for yi in y] + x = _center(x, n) + y = _center(y, n) sxy = sumprod(x, y) sxx = sumprod(x, x) diff --git a/Lib/test/test_statistics.py b/Lib/test/test_statistics.py index 266d92828fe154..bb6cd8a4f1ce3c 100644 --- a/Lib/test/test_statistics.py +++ b/Lib/test/test_statistics.py @@ -2747,6 +2747,14 @@ def test_different_scales(self): self.assertAlmostEqual(statistics.correlation(x, y), 1) self.assertAlmostEqual(statistics.covariance(x, y), 0.1) + def test_large_offset(self): + # gh-162743: a large common offset must not swallow the signal. + epoch = 1_700_000_000_000_000_000 + event = [epoch + 256, epoch + 512, epoch + 768] + received = [t + 1024 for t in event] + self.assertAlmostEqual(statistics.correlation(event, received), 1.0) + self.assertAlmostEqual(statistics.covariance(event, received), 65536.0) + def test_sqrtprod_helper_function_fundamentals(self): # Verify that results are close to sqrt(x * y) for i in range(100): diff --git a/Misc/NEWS.d/next/Library/2026-11-28-00-00-00.gh-issue-162743.aBcDeF.rst b/Misc/NEWS.d/next/Library/2026-11-28-00-00-00.gh-issue-162743.aBcDeF.rst new file mode 100644 index 00000000000000..f6c419c20990a1 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-28-00-00-00.gh-issue-162743.aBcDeF.rst @@ -0,0 +1,3 @@ +Fix :func:`statistics.correlation` and :func:`statistics.covariance` +returning incorrect results when the data share a large common offset, +as with timestamp-like values that differ by a small amount.