使用 scipy.interpolate.interp1d 计算 y=0.95 时的 x 值

3

我有两个数组,一个是x,一个是y。这两个数组之间没有关系,但我想能够在线性插值点之间进行插值,使得y=f(x),以便我可以计算出在y = 0.95时的x值。到目前为止,我所使用的方法如下:

import numpy as np
from scipy.interpolate import interp1d    

def NearestValue(array,value):
#returns the index of the element of the array which is closest to value

idx = (np.abs(array-value)).argmin()
return idx

x =[[   0. ],[   9.9],[  19.8],[  31.5],[  41.9],[  49.1],[  59. ],[  70. ],[  80.4],[ 100. ]]

y= [ 0.011905, 0.140795, 0.600562, 0.757247, 0.874564, 0.934559, 0.961719, 0.986099,  0.990284, 0.998254]

f = interp1d(x,y)

x_new  = np.linspacex(x[0],x[9],1000)
y_new = f(x_new)

NearestIndex = NearestValue(y_new,0.95)

x_nearest = x_new[NearestIndex]

这个方法会返回x_new中与0.95最接近的y_new值所对应的数值。是否有办法计算出y值恰好为0.95时对应的x值?


在我的当前scipy实现(0.19.0)中,您的代码由于“x”和“y”的维度而出现错误。请还要检查您的函数缩进是否丢失。请编辑您的问题。 - Ramon Crehuet
1个回答

2

我认为这很简单,只需要将x作为y的函数进行插值(我还需要将x展平以避免出错):

import numpy as np
from scipy.interpolate import interp1d    

def NearestValue(array,value):
    #returns the index of the element of the array which is closest to value

    idx = (np.abs(array-value)).argmin()
    return idx

x =[[   0. ],[   9.9],[  19.8],[  31.5],[  41.9],[  49.1],[  59. ],[  70. ],[  80.4],[ 100. ]]

y= [ 0.011905, 0.140795, 0.600562, 0.757247, 0.874564, 0.934559, 0.961719, 0.986099,  0.990284, 0.998254]

f = interp1d(y, np.array(x).flatten())

print (f(0.95))
for i,_ in enumerate(y):
    print (_,  x[i][0], f(_))

编辑:我已经自行替换了回答者提供的最后一行代码,用三行代码展示了这个解决方案的优美之处。它们产生以下输出。

54.728346833578776
0.011905 0.0 0.0
0.140795 9.9 9.9
0.600562 19.8 19.8
0.757247 31.5 31.5
0.874564 41.9 41.9
0.934559 49.1 49.1
0.961719 59.0 59.0
0.986099 70.0 70.0
0.990284 80.4 80.4
0.998254 100.0 100.0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接