PIXELBANKv8.2.1
Menu

Simple Linear Regression

Implement simple linear regression using the closed-form (least squares) solution.

Given a list of xx values and a list of yy values, compute the slope mm and intercept bb of the best-fit line y=mx+by = mx + b.

The formulas are: m=nxiyixiyinxi2(xi)2m = \frac{n\sum x_i y_i - \sum x_i \sum y_i}{n\sum x_i^2 - (\sum x_i)^2} b=yˉmxˉb = \bar{y} - m\bar{x}

where nn is the number of data points and xˉ\bar{x}, yˉ\bar{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\sum x_i = 1 + 2 + 3 + 4 + 5 = 15, yi=2+4+5+4+5=20\sum y_i = 2 + 4 + 5 + 4 + 5 = 20, xiyi=12+24+35+44+55=2+8+15+16+25=66\sum x_i y_i = 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\sum x_i^2 = 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 1 + 4 + 9 + 16 + 25 = 55.
  • Then, we calculate the slope mm using the formula: m=5661520555152=330300275225=3050=0.6m = \frac{5*66 - 15*20}{5*55 - 15^2} = \frac{330 - 300}{275 - 225} = \frac{30}{50} = 0.6.
  • Next, we calculate the means: xˉ=155=3\bar{x} = \frac{15}{5} = 3 and yˉ=205=4\bar{y} = \frac{20}{5} = 4, and then the intercept b=yˉmxˉ=40.63=41.8=2.2b = \bar{y} - m\bar{x} = 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)(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

Test Results

0/0
Run code to see test results.