8000 GH-102670: Use sumprod() to simplify, speed up, and improve accuracy of statistics functions by rhettinger · Pull Request #102649 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

GH-102670: Use sumprod() to simplify, speed up, and improve accuracy of statistics functions #102649

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Mar 14, 2023
Prev Previous commit
Next Next commit
Use sumprod() in linear_regression().
  • Loading branch information
rhettinger committed Mar 13, 2023
commit 16b2745301a6212dd9eb0cce646255fc35bccb9d
10 changes: 6 additions & 4 deletions Lib/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -1134,13 +1134,15 @@ def linear_regression(x, y, /, *, proportional=False):
if n < 2:
raise StatisticsError('linear regression requires at least two data points')
if proportional:
sxy = fsum(xi * yi for xi, yi in zip(x, y))
sxx = fsum(xi * xi for xi in x)
sxy = sumprod(x, y)
sxx = sumprod(x, x)
else:
xbar = fsum(x) / n
ybar = fsum(y) / n
sxy = fsum((xi - xbar) * (yi - ybar) for xi, yi in zip(x, y))
sxx = fsum((d := xi - xbar) * d for xi in x)
centered_x = [xi - xbar for xi in x]
centered_y = (yi - ybar for yi in y)
sxy = sumprod(centered_x, centered_y)
sxx = sumprod(centered_x, centered_x)
try:
slope = sxy / sxx # equivalent to: covariance(x, y) / variance(x)
except ZeroDivisionError:
Expand Down
0