问题描述
我正在尝试使用 scipy 的插值函数反转插值函数.假设我创建了一个插值函数,
I am trying to invert an interpolated function using scipy's interpolate function. Let's say I create an interpolated function,
import scipy.interpolate as interpolate
interpolatedfunction = interpolated.interp1d(xvariable,data,kind='cubic')
当我指定a时,是否有一些函数可以找到x:
Is there some function that can find x when I specify a:
interpolatedfunction(x) == a
换句话说,我希望我的插值函数等于 a;xvariable 的值是多少,使得我的函数等于 a?"
In other words, "I want my interpolated function to equal a; what is the value of xvariable such that my function is equal to a?"
我很感激我可以用一些数值方案来做到这一点,但有没有更直接的方法?如果插值函数在 xvariable 中是多值的怎么办?
I appreciate I can do this with some numerical scheme, but is there a more straightforward method? What if the interpolated function is multivalued in xvariable?
推荐答案
创建插值函数interp_fn
后,可以找到x
的值,其中interp_fn(x) == a
根据函数的根
After creating an interpolated function interp_fn
, you can find the value of x
where interp_fn(x) == a
by the roots of the function
interp_fn2 = lambda x: interp_fn(x) - a
在 scipy.optimize
中有许多选项可以找到根.例如,使用牛顿法,初始值从 10 开始:
There are number of options to find the roots in scipy.optimize
. For instance, to use Newton's method with the initial value starting at 10:
from scipy import optimize
optimize.newton(interp_fn2, 10)
实际例子
创建一个插值函数,然后找到fn(x) == 5
import numpy as np
from scipy import interpolate, optimize
x = np.arange(10)
y = 1 + 6*np.arange(10) - np.arange(10)**2
y2 = 5*np.ones_like(x)
plt.scatter(x,y)
plt.plot(x,y)
plt.plot(x,y2,'k-')
plt.show()
# create the interpolated function, and then the offset
# function used to find the roots
interp_fn = interpolate.interp1d(x, y, 'quadratic')
interp_fn2 = lambda x: interp_fn(x)-5
# to find the roots, we need to supply a starting value
# because there are more than 1 root in our range, we need
# to supply multiple starting values. They should be
# fairly close to the actual root
root1, root2 = optimize.newton(interp_fn2, 1), optimize.newton(interp_fn2, 5)
root1, root2
# returns:
(0.76393202250021064, 5.2360679774997898)
这篇关于反转插值以给出与所需插值函数值相关联的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!