Search code examples
pythonnumpyscipyinterpolationextrapolation

Replacement for legacy scipy.interpolate.interp1d for piecewise linear interpolation with extrapolation


The documentation for scipy.interpolate.interp1d tells me

This class is considered legacy and will no longer receive updates. This could also mean it will be removed in future SciPy versions. For a guide to the intended replacements for interp1d see 1-D interpolation.

The linked page basically tells me to use numpy.interp for piecewise linear interpolation. However, as far as I can tell, that function does not support linear extrapolation beyond the data range (only constant extrapolation). This makes it an inadequate replacement where linear extrapolation is desired.

What is the recommended replacement for interp1d in those cases, now that it is no longer recommended for new code?

Here's an example showing what I want to achieve (orange) and what np.interp does (green).

import numpy as np
from scipy.interpolate import interp1d
from matplotlib import pyplot as plt

a = np.linspace(0, 10, 11)
b = np.sin(a)
plt.plot(a, b, 'o')

x = np.linspace(-2, 12, 51)

y = interp1d(a, b, fill_value='extrapolate')(x)
plt.plot(x, y, '+-')

y = np.interp(x, a, b)
plt.plot(x, y, 'x:')

example output


Solution

  • >>> spl= make_interp_spline(x, y, k=1) # linear
    >>> ynew = spl(xnew)