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
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
Make zip
a friend
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 = [x for _, x in sorted(zip(y, x))]
y.sort()
xi = np.interp(60, y, x)
print(xi)