summaryrefslogtreecommitdiffstats
path: root/Lib/statistics.py
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/statistics.py')
-rw-r--r--Lib/statistics.py31
1 files changed, 24 insertions, 7 deletions
diff --git a/Lib/statistics.py b/Lib/statistics.py
index 4f3ab49..5c3f77d 100644
--- a/Lib/statistics.py
+++ b/Lib/statistics.py
@@ -937,13 +937,13 @@ def correlation(x, y, /):
LinearRegression = namedtuple('LinearRegression', ('slope', 'intercept'))
-def linear_regression(x, y, /):
+def linear_regression(x, y, /, *, proportional=False):
"""Slope and intercept for simple linear regression.
Return the slope and intercept of simple linear regression
parameters estimated using ordinary least squares. Simple linear
regression describes relationship between an independent variable
- *x* and a dependent variable *y* in terms of linear function:
+ *x* and a dependent variable *y* in terms of a linear function:
y = slope * x + intercept + noise
@@ -961,21 +961,38 @@ def linear_regression(x, y, /):
>>> linear_regression(x, y) #doctest: +ELLIPSIS
LinearRegression(slope=3.09078914170..., intercept=1.75684970486...)
+ If *proportional* is true, the independent variable *x* and the
+ dependent variable *y* are assumed to be directly proportional.
+ The data is fit to a line passing through the origin.
+
+ Since the *intercept* will always be 0.0, the underlying linear
+ function simplifies to:
+
+ y = slope * x + noise
+
+ >>> y = [3 * x[i] + noise[i] for i in range(5)]
+ >>> linear_regression(x, y, proportional=True) #doctest: +ELLIPSIS
+ LinearRegression(slope=3.02447542484..., intercept=0.0)
+
"""
n = len(x)
if len(y) != n:
raise StatisticsError('linear regression requires that both inputs have same number of data points')
if n < 2:
raise StatisticsError('linear regression requires at least two data points')
- 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)
+ if proportional:
+ sxy = fsum(xi * yi for xi, yi in zip(x, y))
+ sxx = fsum(xi * xi for xi in 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)
try:
slope = sxy / sxx # equivalent to: covariance(x, y) / variance(x)
except ZeroDivisionError:
raise StatisticsError('x is constant')
- intercept = ybar - slope * xbar
+ intercept = 0.0 if proportional else ybar - slope * xbar
return LinearRegression(slope=slope, intercept=intercept)