Interpolation is the process of estimating unknown values that fall between known values. SciPy's
interpolate
module provides several methods for interpolation.
Create Sample Data: We'll create some sample data points that we want to interpolate between.
Interpolate the Data: We'll use scipy.interpolate.interp1d
to
create an interpolation function.
Plot the Results: We'll use matplotlib
to visualize the
original data points and the interpolated values.
import numpy as np from scipy.interpolate import interp1d import matplotlib.pyplot as plt # Step 1: Create sample data x = np.linspace(0, 10, num=11, endpoint=True) # 11 points from 0 to 10 y = np.cos(-x**2/9.0) # Some function of x # Step 2: Create an interpolation function f_linear = interp1d(x, y) # Interpolating with more points for a smoother curve x_new = np.linspace(0, 10, num=100, endpoint=True) y_new = f_linear(x_new) # Step 3: Plot the results plt.figure(figsize=(8, 4)) plt.plot(x, y, 'o', label='Original data points') plt.plot(x_new, y_new, '-', label='Linear interpolation') plt.xlabel('x') plt.ylabel('y') plt.legend(loc='best') plt.title('Linear Interpolation using scipy.interpolate.interp1d') plt.show()
Creating Sample Data:
x
is an array of 11 evenly spaced points from 0 to 10.y
is an array of cosine values of -x^2/9.0
.Creating an Interpolation Function:
interp1d(x, y)
creates a linear interpolation function
f_linear
based on the original data points.Interpolating and Plotting:
x_new
is an array of 100 evenly spaced points from 0 to 10 for a smoother
interpolation curve.y_new
is the interpolated values at the points in x_new
.When you run the above code, you'll get a plot showing the original data points and the interpolated curve:
This plot demonstrates how linear interpolation can estimate values between the known data points, resulting in a smooth curve that approximates the underlying function.
SciPy also supports other interpolation methods such as cubic interpolation
(kind='cubic'
) and nearest-neighbor interpolation (kind='nearest'
). You
can specify the interpolation method when creating the interpolation function:
f_cubic = interp1d(x, y, kind='cubic') y_new_cubic = f_cubic(x_new) plt.plot(x_new, y_new_cubic, '--', label='Cubic interpolation') plt.legend(loc='best') plt.show()
This will create and plot a cubic interpolation, which can provide a smoother curve than linear interpolation.