4

I'm having difficulties to perform a spline interpolation on the below set:

import numpy
SOURCE = numpy.array([[1,2,3],[3,4,5], [9,10,11]])
from scipy.interpolate import griddata
from scipy.interpolate import interp1d
input = [0.5,2,3,6,9,15]

The linear interpolation works fine, yet when I replace linear with cubic, I have an error :

f = interp1d(SOURCE[:,0], SOURCE[:,1:], kind="linear", axis=0, bounds_error=False)
f(input)

f = interp1d(SOURCE[:,0], SOURCE[:,1:], kind="cubic", axis=0, bounds_error=False)
ValueError: The number of derivatives at boundaries does not match: expected 1, got 0+0

How can I perform this cubic interpolation ?

Nielsou Akbrg
  • 201
  • 3
  • 13

1 Answers1

9

Your SOURCE data is too short. A cubic spline needs at least four points to interpolate from, but you're only provide three. If you add one more value to SOURCE, it should work more or less as expected:

>>> SOURCE = numpy.array([[1,2,3],[3,4,5], [9,10,11], [12,13,14]])  # added an extra value
>>> f = interp1d(SOURCE[:,0], SOURCE[:,1:], kind="cubic", axis=0, bounds_error=False)
>>> f(input)
array([[nan, nan],
       [ 3.,  4.],
       [ 4.,  5.],
       [ 7.,  8.],
       [10., 11.],
       [nan, nan]])
Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • thanks, I added a bit more data indeed, it's obvious as it needs to approximate the diff for every point... also do you know if there is a possibility to specify the derivate value for extrapolation (either 0 or [ f(x1) - f(x0) ] / [x1 - x0] for regular or clamped splines ? – Nielsou Akbrg May 03 '20 at 20:22
  • 1
    Even I was doing with three points and this problem occured to me. But adding more points solved the issue. Thanks mann! – VARAT BOHARA May 17 '22 at 14:21