How to implement ‘cubic’ 1-D interpolation using SciPy library?

ScipyScientific ComputingProgramming

To implement ‘cubic’ 1-D interpolation using SciPy, we need to specify the kind of interpolation as ‘cubic’ in the ‘kind’ parameter of scipy.interpolate.interp1d class. Let’s see the example below to understand it−

Example

First let’s generate some data to implement interpolation on that −

import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
A = np.linspace(0, 10, num=11, endpoint=True)
B = np.cos(-A**2/9.0)
print (A, B)

Output

The above script will generate the following points between 0 and 4 −

[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.] [ 1. 0.99383351 0.90284967 0.54030231 -0.20550672 -0.93454613 -0.65364362 0.6683999 0.67640492 -0.91113026 0.11527995]

Now, let’s plot these points as follows−

plt.plot(A, B, '.')
plt.show()

Now we need to create an interpolate function based on fixed data points. Let’s create it −

function_interpolate = interp1d(A, B, kind = 'cubic') #providing ‘cubic’ in the parameter ‘kind’.

To see the clear difference of interpolation, we will create a new input of more length by using the same function as used for old input −

Anew = np.linspace(0, 10, num=30, endpoint=True)
plt.plot(A, B, '.', Anew, function_interpolate(Anew), '--')
plt.legend(['data', 'cubic'], loc = 'best')
plt.show()

raja
Published on 24-Nov-2021 11:05:04

Advertisements