Python Keep points in spline interpolation

I wrote code that performs spline interpolation:

x1 = [ 0., 13.99576991, 27.99153981, 41.98730972, 55.98307963, 69.97884954, 83.97461944, 97.97038935, 111.9661593, 125.9619292, 139.9576991, 153.953469 ]
y1 = [ 1., 0.88675318, 0.67899118, 0.50012243, 0.35737022, 0.27081293, 0.18486778, 0.11043095, 0.08582272, 0.04946131, 0.04285015, 0.02901567]

x = np.array(x1) 
y = np.array(y1)

# Interpolate the data using a cubic spline to "new_length" samples
new_length = 50
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

But in the new dataset generated new_xand new_y, the starting points are deleted, only the first and last values ​​are saved. I would like to keep the starting points.

+5
source share
1 answer

Right, linspacewill not generate any of the values x, except those that you pass to it ( x.min()and x.max()).

I don't have a big quick answer, but here is one way to do this:

# Interpolate the data using a cubic spline to "new_length" samples
new_length = 50
interpolated_x = np.linspace(x.min(), x.max(), new_length - len(x) + 2)
new_x = np.sort(np.append(interpolated_x, x[1:-1]))  # include the original points
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

This code uses:

  • np.linspaceto create as many extra points as we need
  • np.appendto combine an array of additional points with reference points from x
  • np.sortto put the combined array in order
+6
source

All Articles