import numpy as np
from numpy import array , poly1d , polyfit
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
# Data points
xdata = array ([2,6,12,18,22,33,40,45,50,57])
ydata = array ([4.5 ,37 ,120 , 100 ,83.9 ,65 ,64 ,66 ,70 ,71])

fig,ax = plt.subplots()
new_x=np.linspace(xdata[0],xdata[-1],num=100)
#linear 
lin = interp1d(xdata , ydata , kind='linear')
new_y=lin(new_x)
ax.plot(new_x,new_y,'--',c='green')
# pure polynomial
coefficients=polyfit(xdata,ydata,len(xdata)-1)
poly=poly1d(coefficients)
new_y=poly(new_x)
ax.plot(new_x,new_y,c='red')
# quadratic spline
qspl=interp1d(xdata , ydata , kind='quadratic')
new_y=qspl(new_x)
ax.plot(new_x,new_y,'--',c='blue')
# cubic spline
cspl=interp1d(xdata , ydata , kind='cubic')
new_y=cspl(new_x)
ax.plot(new_x,new_y,c='m')
# initial points
ax.scatter(xdata,ydata,color='black')
#legend
ax.legend (('linear','polinomial','quadratic spline','cubic spline','data'))
ax.set(xlabel='x',ylabel='y')
plt.title('Interpolation')
plt.savefig('ex259.png', dpi=90)
plt.show()
#value to interpolate
xv=30.0
#linear 
yv_lin = interp1d(xdata , ydata , kind='linear')(xv)
# Pure polynomial
yv_pol = poly1d(polyfit(xdata , ydata , len(xdata)-1))(xv)
# Quadratic spline
yv_qspl = interp1d(xdata , ydata , kind='quadratic')(xv)
# Cubic spline
yv_cspl = interp1d(xdata , ydata , kind='cubic')(xv)
print("y_lin =",yv_lin ,"\ny_pol =",yv_pol ,"\ny_qspl =",yv_qspl ,
      "\ny_cspl =",yv_cspl)

Output:

y_lin = 70.15454545454546 
y_pol = 68.68763643841513 
y_qspl = 67.5966557972689 
y_cspl = 67.74754052923349

Discover more from Tips and Hints for Aerospace Engineers

Subscribe now to keep reading and get access to the full archive.

Continue reading