Mainland
Mainland

Reputation: 4584

Python numpy interpolation gives wrong output

I have an input and output array. I have given below the plot. I want to interpolate value at x=0. I was expecting something like around 16.7 but instead giving 17.4881, peak value. What could be wrong.

Data :

enter image description here

My code:

xdata = [0.101,-0.008,-0.111,-0.209,-0.303]
ydata = [16.5241,16.7987,17.0499,17.2793,17.4885]
xp = np.interp(0,xdata,ydata)
print(xp)

Present output:

  17.4885

Expected output:

16.7 # around from plot

Upvotes: 1

Views: 1375

Answers (1)

fmarm
fmarm

Reputation: 4284

If you look at interp function documentation, it says that

The x-coordinates of the data points, must be increasing if argument period is not specified. Otherwise, xp is internally sorted after normalizing the periodic boundaries with xp = xp % period.

But your xdata is in descending order, so you need to reverse order in xdata and ydata

import numpy as np
xdata = [0.101,-0.008,-0.111,-0.209,-0.303][::-1]
ydata = [16.5241,16.7987,17.0499,17.2793,17.4885][::-1]
xp = np.interp(0,xdata,ydata)
print(xp)
# 16.778545871559633

Upvotes: 4

Related Questions