I have two arrays of data that correspond to x and y values, that I would like to interpolate with a cubic spline.
I have tried to do this, but my interpolated function doesn't pass through my data points.
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d re = np.array([0.2,2,20,200,2000,20000],dtype = float) cd = np.array([103,13.0,2.72,0.800,0.401,0.433],dtype = float) plt.yscale('log') plt.xscale('log') plt.xlabel( "Reynold's number" ) plt.ylabel( "Drag coefficient" ) plt.plot(re,cd,'x', label='Data') x = np.linspace(0.2,20000,200000) f = interp1d(re,cd,kind='cubic') plt.plot(x,f(x)) plt.legend() plt.show()What I end up with looks like this;
Which is clearly an awful representation of my function. What am I missing here?
Thank you.
2 Answers2
You can get the result you probably expect (smooth spline on the log axes) by doing this:
f = interp1d(np.log(re),np.log(cd), kind='cubic')plt.plot(x,np.exp(f(np.log(x))))This will build the interpolation in the log space and plot it correctly. Plot your data on a linear scale to see how the cubic has to flip to get the tail on the left hand side.
1 Comment
The main thing you are missing is thelog scaling on your axes. The spline shown is not an unreasonable result given your input data. Try drawing the plot withplt.xscale('linear') instead ofplt.xscale('log'). Perhaps a cubic spline is not the best interpolation technique, at least on the raw data. A better option may be to interpolate on the log of the data insead.
2 Comments
Explore related questions
See similar questions with these tags.

