rafaelcb21
rafaelcb21

Reputation: 13304

Interpolation technique used in numpy

What is the technique used by the numpy interp() function?

So using the following points

import numpy as np

x = [4.5]
xp = [4, 5, 4, 3]
yp = [2, 4, 6, 5]

result = np.interp(x, xp, yp)

print(result) #result = 5.0

When I find the interpolation of x the value is 4.5

But if my points are these 3 xp = [4, 5, 4] e yp = [2, 4, 6] the value will be 6

import numpy as np

x = [4.5]
xp = [4, 5, 4]
yp = [2, 4, 6]

result = np.interp(x, xp, yp)

print(result) #result = 6.0

Upvotes: 0

Views: 136

Answers (2)

Triki Sadok
Triki Sadok

Reputation: 135

the function np.interp linkes the given points two by two, so it can build a total of (number_of_given_points_in_xp - 1) linear function and constant outside the min and max of xp. and xp usually should be sorted and does not have duplicates. \

In your case it will create 3 linear functions. But you are using value 4 two time which makes the function outputting illogical values:

Here is a typical implementation of the function

xp = [1, 2, 3]
fp = [3, 7, 0]
p=[-2, -1, 1, 1.2, 1.7, 1.9, 2, 2.2, 2.9, 3, 3.1, 3.7, 4] # values to predict and then to plot
plt.plot(p, np.interp(p, xp, fp))
plt.scatter(xp, fp, c='red')
plt.show()

here is the output of my code:

enter image description here

In your case;

xp = [4, 5, 4, 3]
fp = [2, 4, 6, 5]
plt.figure(figsize=(9, 9))
plt.plot([0, 1, 2, 3.5, 4, 5, 5.5, 6, 6.5], np.interp([0, 1, 2, 3.5, 4, 5, 5.5, 6, 6.5], xp, fp))
plt.scatter(xp, fp, c='red')
plt.show()

enter image description here

Upvotes: 2

flawr
flawr

Reputation: 11628

In your input the values in xp are not in ascending order, so for this example the question is moot. Check out the documentation:

xp: 1-D sequence of floats

The x-coordinates of the data points, must be increasing (...)

Upvotes: 2

Related Questions