How to perform cubic spline interpolation in python?

前端 未结 4 867
名媛妹妹
名媛妹妹 2021-01-30 11:44

I have two lists to describe the function y(x):

x = [0,1,2,3,4,5]
y = [12,14,22,39,58,77]

I would like to perform cubic spline interpolation so

4条回答
  •  猫巷女王i
    2021-01-30 12:26

    Short answer:

    from scipy import interpolate
    
    def f(x):
        x_points = [ 0, 1, 2, 3, 4, 5]
        y_points = [12,14,22,39,58,77]
    
        tck = interpolate.splrep(x_points, y_points)
        return interpolate.splev(x, tck)
    
    print(f(1.25))
    

    Long answer:

    scipy separates the steps involved in spline interpolation into two operations, most likely for computational efficiency.

    1. The coefficients describing the spline curve are computed, using splrep(). splrep returns an array of tuples containing the coefficients.

    2. These coefficients are passed into splev() to actually evaluate the spline at the desired point x (in this example 1.25). x can also be an array. Calling f([1.0, 1.25, 1.5]) returns the interpolated points at 1, 1.25, and 1,5, respectively.

    This approach is admittedly inconvenient for single evaluations, but since the most common use case is to start with a handful of function evaluation points, then to repeatedly use the spline to find interpolated values, it is usually quite useful in practice.

提交回复
热议问题