Quadratic Interpolation#

../_images/quad_interp.png

A plot of a quadratic curve interpolated between three reference points#

Whereas the linear method uses two points, a quadratic uses three points and can be written as:-

\[y = a\cdot x^2 + b\cdot x + c\]

for each of the three points \((x_0,y_0), (x_1,y_1), (x_2,y_2)\) this becomes:-

\[\begin{split}y_0 &= f(x_0) = a\cdot x_0^2 + b\cdot x_0 + c\\ y_1 &= f(x_1) = a\cdot x_1^2 + b\cdot x_1 + c\\ y_2 &= f(x_2) = a\cdot x_2^2 + b\cdot x_2 + c\end{split}\]

when solved:-

\[y = y_0 \frac{(x - x_1)(x - x_2)}{(x0 - x_1)(x0 - x_2)} + y_1 \frac{(x - x_0)(x - x_2)}{(x1 - x_0)(x1 - x_2)} + y_2 \frac{(x - x_0)(x - x_1)}{(x2 - x_0)(x2 - x_1)}\]

The three points must not be colinear but need not be equidistant. If the middle point's y-value is either larger than or smaller than both the outer points' y-values then it will generate a vertical parabola. A horizontal parabola will be made if the mid point x-value is larger than both the outer points' x-values.

Check how the equation has progressed from the linear equation.

In the example a quadratic is fitted through three points, which is then plotted.

Show/Hide Code quad_interp.py

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

sns.set_theme()

def quad_interp(x0, y0, x1, y1, x2, y2, x):
    y = y0 * (x - x1)*(x - x2)/((x0 - x1)*(x0 - x2)) + \
            y1 * (x - x0)*(x - x2)/((x1 - x0)*(x1 - x2)) + \
            y2 * (x - x0)*(x - x1)/((x2 - x0)*(x2 - x1))
    return y


x = [1, 2, 4]
y = [2, 3, -1]

xs = np.linspace(0,5,100)

ys = quad_interp(x[0],y[0],x[1],y[1],x[2],y[2], xs)
#print(ys)

#create plot of x vs. y
plt.plot(x, y, 'or', label='three points')
plt.plot(xs, ys, '-b', label='interpolation')

plt.xlabel(r'$x$')
plt.ylabel(r'$f(x)$')
plt.title('Quadratic Interpolation')
plt.legend()

plt.show()
#plt.savefig('../../figures/quad_interp.png')