简体   繁体   中英

Interpolating Data Using SciPy

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.

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.

The main thing you are missing is the log scaling on your axes. The spline shown is not an unreasonable result given your input data. Try drawing the plot with plt.xscale('linear') instead of plt.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM