Python numpy插值给出错误的输出/值

55ooxyrt  于 2023-01-13  发布在  Python
关注(0)|答案(3)|浏览(151)

我想在y = 60处插入一个值,我期望的输出应该在0.27范围内
我的代码:

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)

输出:

4.75

预期产出:

0.27
a1o7rhls

a1o7rhls1#

你必须根据你的xp(在你的例子中是y)对输入数组排序

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
8oomwypt

8oomwypt2#

你必须sort()两个列表,不仅x坐标,而且y坐标:

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

qoefvg9y3#

你对x数组排序,但不对y数组排序。文档(here)说:
单调递增样本点的一维线性插值。
但是你有一个单调递减的函数。

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)

退货

0.296484375

相关问题