Search code examples
pythonscipyinterpolation

Why does quadratic interpolation on four points produce a cubic plot?


Consider the following Python program:

import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

# Define your four data points
x = np.array([0, 1, 2, 3])  # x-coordinates of the points
y = np.array([0, 1, 0, 1])  # y-coordinates of the points

# Create the interpolation function with quadratic interpolation
f = interp1d(x, y, kind='quadratic')

# Generate a finer grid of x values for plotting
x_interp = np.linspace(min(x), max(x), 1000)

# Compute the corresponding y values using the interpolation function
y_interp = f(x_interp)

# Plot the data points and the interpolated curve
plt.scatter(x, y, label='Data Points')
plt.plot(x_interp, y_interp, label='Quadratic Interpolation')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Quadratic Interpolation with 4 Data Points')
plt.show()

This is the resulting plot:

enter image description here

That is not quadratic, but rather that appears to be a cubic polynomial.

What is happening inside interp1d() and why is the resulting curve not quadratic?


Solution

  • For scipy.interpolate.interp1d, the kind parameter specifies what kind of spline to use. When we talk about interpolation using splines, that usually means it's a piecewise interpolation.

    So, in this case, by choosing a quadratic interpolation method, every two points will be connected by a quadratic function. Now, if we were to just leave the problem like that, it would be underdefined (more variables than equations), so that is handled using boundary conditions (which I won't get into).

    If you want to interpolate your data with a single quadratic equation, you'll have an issue since a quadratic equation is specified by 3 points while you have 4. Instead, as mentioned in the comments, you'd have to perform curve fitting (i.e. regression), not interpolation.