📘
Simple Linear Regression
Implement simple linear regression using the closed-form (least squares) solution.
Given a list of x values and a list of y values, compute the slope m and intercept b of the best-fit line y=mx+b.
The formulas are: m=n∑xi2−(∑xi)2n∑xiyi−∑xi∑yi b=yˉ−mxˉ
where n is the number of data points and xˉ, yˉ are the means.
Return a tuple (slope, intercept), both rounded to 4 decimal places.
Example:
Input:
X = [1, 2, 3, 4, 5] y = [2, 4, 5, 4, 5]
Output:
(0.6, 2.2)
Reasoning:
- First, we calculate the necessary sums: ∑xi=1+2+3+4+5=15, ∑yi=2+4+5+4+5=20, ∑xiyi=1∗2+2∗4+3∗5+4∗4+5∗5=2+8+15+16+25=66, and ∑xi2=12+22+32+42+52=1+4+9+16+25=55.
- Then, we calculate the slope m using the formula: m=5∗55−1525∗66−15∗20=275−225330−300=5030=0.6.
- Next, we calculate the means: xˉ=515=3 and yˉ=520=4, and then the intercept b=yˉ−mxˉ=4−0.6∗3=4−1.8=2.2.
- The final output is a tuple of the slope and intercept, both rounded to 4 decimal places: (0.6,2.2).
Constraints:
- Input: two lists of equal length (at least 2 elements)
- Return a tuple (slope, intercept) rounded to 4 decimal places
- Use only basic Python (no numpy)
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.