Numpy interp decreases xp

I want to interpolate a numpy array, and np.interp does almost what I want:

interp(x, xp, fp, left=None, right=None) One-dimensional linear interpolation. 

Except for this bit:

Does not verify that the x-coordinate sequence xp increasing. If xp does not increase, the results are meaningless.

My xp is decreasing, so it’s better: By reversing the direction of xp and fp:

 np.interp(x, xp[::-1], fp[::-1]) 

or invert x and xp:

 np.interp(-x, -xp, fp) 

Or is there an even better way?

+7
python numpy interpolation
source share
2 answers

Thanks to everyone who contributed, especially @Jaime.

I experimented a bit and came to this conclusion:

1) In addition to rounding errors, both methods mentioned by me have the same result.

2) They both take a lot of time

3) I tried the scipy version, but it would reject the take_sorted flag. My scipy version may be outdated. I suspect that if this flag is raised, scipy internally sorts arrays. But the values ​​are sorted only in the opposite direction, so this does not need to be done.

In any case, I will use the reverse direction method:

 np.interp(x, xp[::-1], fp[::-1]) 

Just remember that in this case you will also have to undo left and right if you need them.

+4
source share

If you have access to Scipy , you can use the interp1d function, which has the keyword assume_sorted=False to handle decreasing arrays.

Edit: this solution handles both 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() 
+3
source share

All Articles