如何提高此类评估结构的 G(x,y) 性能:
from scipy import integrate,infty
def f(x):
"""
Some complicated function
"""
pass
def F(x):
"""
Integration of f
"""
value = integrate.quad(f,-infty,x)
return value
def g(x,y):
"""
Another complicated function which uses F(x)!
"""
pass
def G(x,y):
"""
The function for which I want to improve perfomance
"""
value = integrate.quad(g,-infty,+infty,args=(y))
return value
我想要的是用之前已经完成的对 F(x) 评估的引用来代替它。
编辑
为了清楚起见,使用 scipy.interpolate.interp1d
和装饰器之后,我的代码如下所示:
class interpolate_function():
"""
Returns interpolated function in given range
"""
def __init__(self,tmin=-20,tmax=+20):
self.tmin = tmin
self.tmax = tmax
def __call__(self,expX):
tmin = self.tmin
tmax = self.tmax
from numpy import linspace
t = linspace(tmin,tmax,2000)
import scipy.interpolate as inter
#expX_interp = inter.PchipInterpolator(t,W.expX(t))
from scipy import vectorize
expX = vectorize(expX)
expX_interp = inter.interp1d(t,expX(t),kind='linear')
return expX_interp
from scipy import integrate,infty
def f(x):
"""
Some complicated function
"""
pass
@interpolate_function(tmin=-20,tmax=+20)
def F(x):
"""
Integration of f
"""
value = integrate.quad(f,-infty,x)
return value
def g(x,y):
"""
Another complicated function which uses F(x)!
"""
pass
def G(x,y):
"""
The function for which I want to improve perfomance
"""
value = integrate.quad(g,-infty,+infty,args=(y))
return value
因此除了装饰器之外的主要代码保持不变,但性能提升了3000倍左右。
最佳答案
对于每次调用 F(x)
,您都在 (-infinity, x) 中进行积分,这就是您的瓶颈。相反,我会对一组点进行积分并创建一个插值函数。因此,如果您的 x
值在 0 到 10 之间,您可以执行从无穷大到 0、0.5...9.5、10(如您需要的细网格)的积分并对其进行插值.
编辑:
为了更有效地构建网格,您可以使用积分的加性属性。因此,F(0) = int_infty^0 f(x)、F(1) = F(0) + int_0^1 f(x) 等。只要您跟踪,您可以使用不同大小的网格其中。另外,为了避免奇怪的插值效应,我会使用 pchip
(厄米多项式,总是在边界达到最大值和最小值)或线性插值。
关于python - 提高绩效以返回值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23266740/