I want to interpolate a numpy array, and the np.interp does almost exactly what I want:
interp(x, xp, fp, left=None, right=None)
One-dimensional linear interpolation.
Except for this bit:
Does not check that the x-coordinate sequence
xp
is increasing. Ifxp
is not increasing, the results are nonsense.
My xp is decreasing, so which is better: Reversing the direction of both xp an fp:
np.interp(x, xp[::-1], fp[::-1])
or inverting x and xp:
np.interp(-x, -xp, fp)
Or is there an even better way?
Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x. The x-coordinates at which to evaluate the interpolated values. The x-coordinates of the data points, must be increasing if argument period is not specified.
The np. interp() is a numpy mathematical library function that returns one-dimensional linear interpolation. The interp() function accepts five arguments which are x, xp, fp, left, right, and period and returns float or complex (corresponding to fp) or ndarray.
The function interp1d() is used to interpolate a distribution with 1 variable. It takes x and y points and returns a callable function that can be called with new x and returns corresponding y .
Thanks for all those that have given their input, especially @Jaime.
I have experimented a bit, and came to this conclusion:
1) Apart from rounding errors, both methods mentioned by me have the same result.
2) They both take very much the same amount of time
3) I tried the scipy version, but it would reject the assume_sorted flag. Maybe my version of scipy is outdated. I suspect that if that flag is raised, scipy internally sorts the arrays. But the values are sorted, just in the opposite direction, so it doesn't need to do this.
Anyway, I'll use the reverse-direction method:
np.interp(x, xp[::-1], fp[::-1])
Just remember that in this case, you'll also have to reverse left
and right
, if you need them.
If you have access to Scipy, you could use the function interp1d, which has the keyword assume_sorted=False
to handle decreasing arrays.
Edit: This solution handles both the cases of ordered and non ordered x values.
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
# Decreasing array
x = np.arange(0, 10)[::-1]
y = np.exp(-x/3.0)
# Interpolation object
f = interpolate.interp1d(x, y, assume_sorted = False)
xnew = np.arange(3,5)
ynew = f(xnew) # use interpolation function returned by `interp1d`
plt.plot(x, y, 'o', xnew, ynew, '-')
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With