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
Factor-out common logic in linear_regression
  • Loading branch information
rhettinger committed Mar 13, 2023
commit c51e520b7c8f9f8e14ca6b2537de46f8e42cada2
15 changes: 8 additions & 7 deletions Lib/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -1074,13 +1074,14 @@ def correlation(x, y, /, *, method='linear'):
start = (n - 1) / -2 # Center rankings around zero
x = _rank(x, start=start)
y = _rank(y, start=start)
xbar = fsum(x) / n
ybar = fsum(y) / n
centered_x = [xi - xbar for xi in x] if xbar else x
centered_y = [yi - ybar for yi in y] if ybar else y
sxy = sumprod(centered_x, centered_y)
sxx = sumprod(centered_x, centered_x)
syy = sumprod(centered_y, centered_y)
else:
xbar = fsum(x) / n
ybar = fsum(y) / n
x = [xi - xbar for xi in x]
y = [yi - ybar for yi in y]
sxy = sumprod(x, y)
sxx = sumprod(x, x)
syy = sumprod(y, y)
try:
return sxy / sqrt(sxx * syy)
except ZeroDivisionError:
Expand Down
0