pythonscipyinterpolationcoefficientscubic-spline

scipy.interpolate.make_interp_spline how to retrieve all the coefficients?


I have the following program:

nknots = 4
x_i = [0, 1, 2, 3]
y_i = [1, np.exp(1), np.exp(2), np.exp(3)]
coeff = interpolate.make_interp_spline(x_i, y_i, bc_type="natural")

I want to construct a cubic spline using the knots whose coordinates are given by x_i and y_i arrays. However, I'm having a hard time obtaining all the coefficients. A cubic spline function has the following form:

y_i(x) = a + b*(x - x_i) + c*(x - x_i)^2 + d*(x - x_i)^3

When I do

print(coeff(x_i))

I get only the array of a values:

[ 1.          2.71828183  7.3890561  20.08553692]

However, I'm missing the arrays for the b, c, and d coefficients. How do I extract those? Or are there steps I'm missing? I read the scipy documentation on make_interp_spline but I didn't understand how to get the b, c and d coefficients.


Solution

  • I'd recommend checking out interpolate.CubicSpline. It's much more convenient if what you're after are the polynomial coefficients. Using your variables:

    spl = interpolate.CubicSpline( x_i, y_i )
    spl.c
    
    array([[-1.57973952e-01,  2.93118310e-01, -1.35144359e-01],
           [ 1.11022302e-16, -4.73921855e-01,  4.05433076e-01],
           [-3.01723742e-01, -7.75645598e-01, -8.44134377e-01],
           [ 1.00000000e+00,  5.40302306e-01, -4.16146837e-01]])
    

    see the PPoly doc for how the piecewise polynomial coefficients are stored.

    Addendum: It's possible to extract the coefficients from the output of make_interp_spline, but it's not straightforward it requires an extra step described by @ev-br because "coefficients" for BSplines (emphasis on the B) are not the same as the polynomial coefficients.