Spline Interpolation- Scipy

 #Spline interpolation using Scipy.

from scipy.interpolate import CubicSpline

import numpy as np

import matplotlib.pyplot as plt

x = [1, 2, 3]

y = [-8, -1, 18]

f = CubicSpline(x, y, bc_type='natural')

x_new = np.linspace(1, 3, 100)

y_new = f(x_new)

print(f(2.5))

plt.plot(x_new, y_new, 'b')

plt.plot(x, y, 'ro')

plt.title('Cubic Spline Interpolation')

plt.xlabel('x')

plt.ylabel('y')

plt.show()


Output Screen:

7.375


Plotting the solution of example 5.3  using pylab

#Example 5.1,5.3 SS Satry
from pylab import* 
x = [1,2,3]
y = [-8,-1,18]
x1=linspace(1,2,100)
y1=3*(x1-1)**3-8*(2-x1)-4*(x1-1) #cubic spline
y2=7*x1-15   #linear
y5=x1**3-9  #actual function

x2=linspace(2,3,100)
y4=3*(3-x2)**3+22*x2-48  #cubic spline
y3=19*x2-39   #linear
y6=x2**3-9  #actual function
plot(x, y, 'o','data')

plot(x1,y1,'b-')
plot(x2,y4,'b-') #cubic spline -blue

plot(x1,y2,'r--')
plot(x2,y3,'r--') #linear -red

plot(x1,y5,'g-')
plot(x2,y6,'g-')   #actual function - green
show()

Output Screen


Another Example:

 
from scipy.interpolate import interp1d
import numpy as np
x =[0,1,2,3]
y =[2,-6,-8,2]

f = interp1d(x, y)
f2 = interp1d(x, y, kind='cubic')
xnew =np.linspace(0,3,100)

import matplotlib.pyplot as plt
plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
plt.legend(['data', 'linear', 'cubic'], loc='best')
plt.show()


Output:








Comments