Fitting a line to noisy points is the simplest and most common least-squares problem.
What to build
Fit the least-squares line y = m·x + c to a set of points and report how well it fits.
Requirements
- Read n and the n points.
- Compute the slope m and the intercept c with the least-squares formulas.
- Print m, c and the sum of squared errors with 4 decimal places.
Input
A whole number n (2 to 20), then n lines each with two numbers x and y (decimals). The x values are not all equal.
Output
Three lines: slope M, intercept C and error E, each to 4 decimal places.
Constraints
All numbers are between -100 and 100.
Example
Input:
4
1 2
2 4
3 5
4 8
Output:
slope 1.9000
intercept 0.0000
error 0.7000
Why it works
Setting the error vector perpendicular to the columns x and 1 gives two equations in m and c, whose solution is the pair of formulas. Among all lines it has the smallest sum of squared errors.
Examples
4 1 2 2 4 3 5 4 8
slope 1.9000 intercept 0.0000 error 0.7000
3 0 1 1 3 2 5
slope 2.0000 intercept 1.0000 error 0.0000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Use m = (n·Σxy − Σx·Σy) ÷ (n·Σx² − (Σx)²) and c = (Σy − m·Σx) ÷ n.
Hint 2
The squared error is the sum of (y − (m·x + c))² over the points.
Hint 3
Print with `round(v, 4) + 0.0` then `:.4f`.
Solution
Show one correct solution (try it yourself first)
n = int(input())
pts = [[float(v) for v in input().split()] for _ in range(n)]
sx = sum(p[0] for p in pts)
sy = sum(p[1] for p in pts)
sxx = sum(p[0] * p[0] for p in pts)
sxy = sum(p[0] * p[1] for p in pts)
m = (n * sxy - sx * sy) / (n * sxx - sx * sx)
c = (sy - m * sx) / n
err = sum((p[1] - (m * p[0] + c)) ** 2 for p in pts)
def r(v):
return f"{round(v, 4) + 0.0:.4f}"
print("slope", r(m))
print("intercept", r(c))
print("error", r(err))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step