Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy interp decreasing xp

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. If xp 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?

like image 372
chw21 Avatar asked Mar 02 '15 03:03

chw21


People also ask

What does Numpy interp return?

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.

How does NP interp work?

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.

How do you interpolate data in Python?

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 .


2 Answers

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.

like image 74
chw21 Avatar answered Sep 28 '22 07:09

chw21


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()
like image 38
hakanc Avatar answered Sep 28 '22 07:09

hakanc