Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Open In Colab

Introduction to Polynomial Fitting

Let’s return to our polynomial fitting armed with our new tool, and use it to separate the order of the polynomial from the number of data points.

An nn th degree polynomial,

y(x)=anxn+an−1xn−1…a2x2+a1x+a0y(x) = a_n x^n + a_{n-1} x^{n-1} \dots a_2 x^2 + a_1 x +a_0

can be applied to mm data points,

y(xi)=anxin+an−1xin−1…a2xi2+a1xi+a0=yiy(x_i) = a_n x_i^n + a_{n-1} x_i^{n-1} \dots a_2 x_i^2 + a_1 x_i +a_0 = y_i

to generate an m×nm \times n matrix, multiplied by an nn vector of polynomial coefficients to equal an mm vector of data:

[1x1x12⋯x1n1x2x22⋯x2n⋮⋮⋮⋱⋮1xmxm2⋯xmn][a0a1a2⋮an]=[y1y2y3⋮ym]\begin{aligned} \begin{bmatrix} 1 & x_1 & x_1^2 & \cdots & x_1^n \\ 1 & x_2 & x_2^2 & \cdots & x_2^n \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 1 & x_m & x_m^2 & \cdots & x_m^n \end{bmatrix} \begin{bmatrix} a_0 \\ a_1 \\ a_2 \\ \vdots \\ a_n \end{bmatrix} = \begin{bmatrix} y_1 \\ y_2 \\ y_3 \\ \vdots \\ y_m \end{bmatrix} \end{aligned}

Example: polynomial fitting

Let’s generate some noisy data from a known 4th order polynomial. We’ll add normally distributed noise to the true function values.

Fitting a Cubic Polynomial

We can solve for the polynomial coefficients directly using the pseudoinverse of the Vandermonde matrix, or using numpy.polyfit. Let’s compare them and plot the result for a 3rd degree (cubic) polynomial.

Fitting Polynomials of Varying Degrees

Let’s fit polynomials from degree 1 to 10 and calculate the residual norm for each.

Even though the true underlying function is 4th order, adding higher-order terms will always reduce the residual error on the training data. This makes it non-trivial to determine the true order just by looking at the error! Let’s plot all of them: