Best parabola by normal equations

The same normal equations that fit a line also fit a parabola. You only need more columns.

What to build

Fit the least-squares parabola y = c0 + c1·x + c2·x² to some points.

Requirements

  • Read n points with whole-number coordinates.
  • Build and solve the 3 × 3 normal equations AᵀA·c = Aᵀy exactly.
  • Print c0, c1 and c2 with 4 decimal places.

Input

A whole number n (3 to 8), then n lines each with two whole numbers x and y. At least three x values are different.

Output

Three lines: c0 V, c1 V and c2 V, each to 4 decimal places.

Constraints

All numbers are between -20 and 20.

Example

Input:

3
0 1
1 2
2 5

Output:

c0 1.0000
c1 0.0000
c2 1.0000

Why it works

The columns 1, x and x² form the matrix A. The best fit makes the error perpendicular to each column, which means AᵀA·c = Aᵀy. Entry (i, j) of AᵀA is the sum of x to the power i + j, so the system is built from power sums.

Examples

Example 1 · Input
3
0 1
1 2
2 5
Expected output
c0 1.0000
c1 0.0000
c2 1.0000
Example 2 · Input
5
-2 4
-1 1
0 0
1 1
2 4
Expected output
c0 0.0000
c1 0.0000
c2 1.0000

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Build the sums S_k = Σ xᵏ for k = 0 to 4 and T_k = Σ xᵏ·y for k = 0 to 2.

Hint 2

The normal equations are a 3 × 3 system: row i is S_i, S_(i+1), S_(i+2) and the right-hand side T_i.

Hint 3

Solve the system with Fraction elimination, then print each coefficient with `round(float(v), 4) + 0.0`.

Solution

Show one correct solution (try it yourself first)
from fractions import Fraction

n = int(input())
pts = [[int(v) for v in input().split()] for _ in range(n)]
S = [sum(p[0] ** k for p in pts) for k in range(5)]
T = [sum(p[0] ** k * p[1] for p in pts) for k in range(3)]
m = [[Fraction(S[i + j]) for j in range(3)] + [Fraction(T[i])] for i in range(3)]
for col in range(3):
    pivot = next(r for r in range(col, 3) if m[r][col] != 0)
    m[col], m[pivot] = m[pivot], m[col]
    for r in range(3):
        if r != col and m[r][col] != 0:
            f = m[r][col] / m[col][col]
            m[r] = [a - f * b for a, b in zip(m[r], m[col])]
for i in range(3):
    v = m[i][3] / m[i][i]
    print(f"c{i} {round(float(v), 4) + 0.0:.4f}")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Projections and least squares →