Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d4ac094

Browse files
authored
Minor accuracy improvement for statistics.correlation() (GH-107781)
1 parent f9e3ff1 commit d4ac094

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

Lib/statistics.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1004,6 +1004,14 @@ def _mean_stdev(data):
10041004
# Handle Nans and Infs gracefully
10051005
return float(xbar), float(xbar) / float(ss)
10061006

1007+
def _sqrtprod(x: float, y: float) -> float:
1008+
"Return sqrt(x * y) computed with high accuracy."
1009+
# Square root differential correction:
1010+
# https://www.wolframalpha.com/input/?i=Maclaurin+series+sqrt%28h**2+%2B+x%29+at+x%3D0
1011+
h = sqrt(x * y)
1012+
x = sumprod((x, h), (y, -h))
1013+
return h + x / (2.0 * h)
1014+
10071015

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

@@ -1083,7 +1091,7 @@ def correlation(x, y, /, *, method='linear'):
10831091
sxx = sumprod(x, x)
10841092
syy = sumprod(y, y)
10851093
try:
1086-
return sxy / sqrt(sxx * syy)
1094+
return sxy / _sqrtprod(sxx, syy)
10871095
except ZeroDivisionError:
10881096
raise StatisticsError('at least one of the inputs is constant')
10891097

0 commit comments

Comments
 (0)