【发布时间】:2014-04-24 10:48:54
【问题描述】:
对于这种类型的评估结构,如何提高 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 倍。
【问题讨论】: