8000 Minor accuracy improvement for statistics.correlation() by rhettinger · Pull Request #107781 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

Minor accuracy improvement for statistics.correlation() #107781

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 3 commits into from
Aug 8, 2023
Merged
Changes from 1 commit
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
Next Next commit
Reduce round-off error in statistics.correlation()."
  • Loading branch information
rhettinger committed Aug 7, 2023
commit 22f151eef41f77ff984f8e6d1ef7440a56eb421c
8 changes: 7 additions & 1 deletion Lib/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -1004,6 +1004,12 @@ def _mean_stdev(data):
# Handle Nans and Infs gracefully
return float(xbar), float(xbar) / float(ss)

def _sqrtprod(x: float, y: float) -> float:
"Return sqrt(x * y) computed with high accuracy."
h = sqrt(x * y)
x = sumprod((x, h), (y, -h))
return h + x / (2.0 * h)


# === Statistics for relations between two inputs ===

Expand Down Expand Up @@ -1083,7 +1089,7 @@ def correlation(x, y, /, *, method='linear'):
sxx = sumprod(x, x)
syy = sumprod(y, y)
try:
return sxy / sqrt(sxx * syy)
return sxy / _sqrtprod(sxx, syy)
except ZeroDivisionError:
raise StatisticsError('at least one of the inputs is constant')

Expand Down
0