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

Expand All @@ -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)


Expand Down Expand Up @@ -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)
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 @@ -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):
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Loading