0

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;

enter image description here

Which is clearly an awful representation of my function. What am I missing here?

Thank you.

askedOct 28, 2015 at 17:50
jm22b's user avatar

2 Answers2

2

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.

answeredOct 28, 2015 at 18:02
chthonicdaemon's user avatar
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I see why I was getting a 'funny' result now. Thank you.
1

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.

answeredOct 28, 2015 at 17:59
Mad Physicist's user avatar

2 Comments

I think I do have logarithmic axes, or am I misunderstanding you?
You do. That is why the fit looks so terrible.

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.