简体   繁体   中英

Python numpy interpolation gives wrong output/value

I want to interpolate a value at y=60, the output I'm expecting should something in the region of 0.27

My code:

x = [4.75, 2.00, 0.850, 0.425, 0.250, 0.180, 0.150, 0.075]
y = [100, 94.5, 86.3, 74.1, 54.9, 38.1, 9.3, 1.7]
x.sort()
xi = np.interp(60, y, x)

Output:

4.75

Expected output:

0.27

you have to sort the input arrays based on your xp (y in your case)

import numpy as np

x = [4.75, 2.00, 0.850, 0.425, 0.250, 0.180, 0.150, 0.075]
y = [100, 94.5, 86.3, 74.1, 54.9, 38.1, 9.3, 1.7]
sort_idx = np.argsort(y)
x_sorted = np.array(x)[sort_idx]
y_sorted = np.array(y)[sort_idx]
xi = np.interp(60, y_sorted, x_sorted)
print(xi)
0.296484375

You have to sort() both lists, not only x coordinates but also y coordinates:

x.sort()
y.sort()
xi = np.interp(60, y, x)
print(xi)
## 0.296484375

you sort your x array, but not the y array. The documentation ( here ) says:

One-dimensional linear interpolation for monotonically increasing sample points.

But you have a monotonously decreasing function.

x = np.array([4.75, 2.00, 0.850, 0.425, 0.250, 0.180, 0.150, 0.075])
x.sort()
y = np.array([100, 94.5, 86.3, 74.1, 54.9, 38.1, 9.3, 1.7])
y.sort()
xi = np.interp(60, y, x)
print(xi)

returns

0.296484375

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM