Simple OLS Linear Regression Fitting
Math & Bit ManipulationAuto-graded · 21 test casesLast updated
Compute the slope and intercept for a univariate linear regression model using ordinary least squares.
Given a set of $n$ paired measurements $(x_1, y_1), (x_2, y_2), \dots, (x_n, y_n)$, determine the slope $m$ and y-intercept $c$ for the linear equation
$$\hat{y} = m x + c$$
that minimizes the total squared residual error $\sum_{i=1}^{n} (y_i - \hat{y}_i)^2$.
The closed-form Ordinary Least Squares (OLS) solutions for the slope $m$ and intercept $c$ are defined as:
$$m = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{\sum_{i=1}^{n} (x_i - \bar{x})^2}$$
$$c = \bar{y} - m \bar{x}$$
where $\bar{x}$ and $\bar{y}$ represent the arithmetic means of the inputs $x$ and targets $y$, respectively.
Implement a function that computes and returns these parameters as a list [slope, intercept].
Constraints
- $2 \le n \le 100,000$
- $-10^6 \le x[i], y[i] \le 10^6$
- $x$ contains at least two distinct values (guaranteeing a non-zero denominator).
- Do not use external machine learning or statistical modeling libraries.
- Standard double-precision floating-point tolerances apply (absolute/relative error within $10^{-6}$).
Examples
Example 1
Input: linear_regression_ols([1, 2, 3], [2, 4, 6])
Output: [2, 0]
Example 2
Input: linear_regression_ols([0, 1, 2, 3], [1, 3, 2, 5])
Output: [1.1, 1.0999999999999999]
Example 3
Input: linear_regression_ols([5, 5, 10], [1, 3, 2])
Output: [0, 2]
Hints
Hint 1
First, iterate over the arrays to calculate the sample averages for x and y.
Hint 2
In a second pass, sum the products of centered deviations (x[i] - mean_x) * (y[i] - mean_y) for the numerator and (x[i] - mean_x)^2 for the denominator.
Hint 3
Avoid the single-pass raw sum formula (n*sum(x*y) - sum(x)*sum(y)) as it can suffer from catastrophic floating-point cancellation when values are large.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The linear model minimizes the sum of squared differences between actual $y_i$ and predicted $\hat{y}_i$. The closed-form analytical solution gives two equations:
- Slope ($m$): $\frac{S_{xy}}{S_{xx}}$ where $S_{xy} = \sum (x_i - \bar{x})(y_i - \bar{y})$ and $S_{xx} = \sum (x_i - \bar{x})^2$.
- Intercept ($c$): $\bar{y} - m \cdot \bar{x}$.
To compute these values stably and efficiently:
- Compute the means $\bar{x}$ and $\bar{y}$ in an initial pass.
- In a second pass, aggregate the centered cross-term $S_{xy}$ and the centered squared term $S_{xx}$.
- Divide $S_{xy} / S_{xx}$ to get the slope $m$, then use $m$ and the means to find $c$.
Numerical Stability Note
While $S_{xy}$ can algebraically be rewritten as $\sum x_i y_i - n \bar{x} \bar{y}$, computing raw sums on large numbers leads to floating-point rounding errors caused by subtractive cancellation. Using mean-centered deviations ($(x_i - \bar{x})$) preserves numerical precision.
Complexity
- Time Complexity: $\mathcal{O}(n)$, performing two simple single-pass loops over the data of size $n$.
- Space Complexity: $\mathcal{O}(1)$ additional memory required beyond input arrays.
from typing import List
def linear_regression_ols(x: List[float], y: List[float]) -> List[float]:
n = len(x)
# Pass 1: Compute means
mean_x = sum(x) / n
mean_y = sum(y) / n
# Pass 2: Accumulate centered covariance and variance terms
sum_xy = 0.0
sum_xx = 0.0
for xi, yi in zip(x, y):
dx = xi - mean_x
dy = yi - mean_y
sum_xy += dx * dy
sum_xx += dx * dx
slope = sum_xy / sum_xx
intercept = mean_y - slope * mean_x
return [slope, intercept]