我正在进行数值积分,其中要集成的函数使用三次样条表示。三次样条曲线在函数MEcompute
中以splc
现在实际进行插值的integrand
需要三次样条数组,因此我需要将splc
传递给这个新函数。在这里,我被困住了。
# function defining the integrand which uses the spline coef array to give interpolated values
def integrand(xpoint):
spline_array=splc
result=interpolate.splev(xpoint,spline_array,der=0)
return result
#----------------------------------------
# function to the matrix element for certain rovibrational state
def MEcompute(psi1,psi2,psi_r, parameter, parameter_r ):
# step 1: gen cubic spline coefs.
splc=interpolate.splrep(parameter_r,parameter,s=0)
# generate interpolated parameter for same xaxis as psi
parameter_interp=interpolate.splev(psi_r,splc,der=0)
# compute the pointwise products
p1=np.multiply(psi1,psi2)
p2=np.multiply(p1,psi_r)
p3=np.multiply(p2,psi_r)
product=np.multiply(p3,parameter_interp)
# step 1: gen cubic spline coefs
splc=interpolate.splrep(psi_r,product,s=0)
# compute the integral using adaptive Quadrature
#result=integrate.quadrature(integrand,0.2,4.48,tol=1.0e-9,maxiter=500)
result=integrate.quadrature(integrand,0.2,4.48,tol=1.0e-9,maxiter=500)
print("<psi1|parameter|psi2> = ",result)
#----------------------------------------
# computing the value
MEcompute(v1,v2,rwave,parameter1,distance)
#----------------------------------------
我收到错误
NameError: name 'splc' is not defined
由于integrand
函数未在函数splc
内启动MEcompute
数组,因此发生了。
现在我有一个想法来克服这个问题:
splc
导出数组MEcompute
可能作为txt文件,然后在integrand
函数中加载此txt文件。这肯定会增加计算时间。有人可以建议更好的方法来做到这一点。
答案 0 :(得分:1)
使用args=
keyword argument将额外参数传递给要集成的函数:
result = integrate.quadrature(integrand, 0.2, 4.48,
tol=1.0e-9, maxiter=500,
args=(splc,))
并修改您的被积函数以接受参数:
def integrand(xpoint, splc):
spline_array=splc
result=interpolate.splev(xpoint,spline_array,der=0)
return result
答案 1 :(得分:1)
您还可以尝试在integrand
中定义MEcompute
。
#----------------------------------------
# function to the matrix element for certain rovibrational state
def MEcompute(psi1,psi2,psi_r, parameter, parameter_r ):
# step 1: gen cubic spline coefs.
splc=interpolate.splrep(parameter_r,parameter,s=0)
# function defining the integrand which uses the spline coef array to give interpolated values
def integrand(xpoint):
return interpolate.splev(xpoint,splc,der=0)
# generate interpolated parameter for same xaxis as psi
parameter_interp=interpolate.splev(psi_r,splc,der=0)
# compute the pointwise products
p1=np.multiply(psi1,psi2)
p2=np.multiply(p1,psi_r)
p3=np.multiply(p2,psi_r)
product=np.multiply(p3,parameter_interp)
# step 1: gen cubic spline coefs
splc=interpolate.splrep(psi_r,product,s=0)
# compute the integral using adaptive Quadrature
#result=integrate.quadrature(integrand,0.2,4.48,tol=1.0e-9,maxiter=500)
result=integrate.quadrature(integrand,0.2,4.48,tol=1.0e-9,maxiter=500)
print("<psi1|parameter|psi2> = ",result)
#----------------------------------------
# computing the value
MEcompute(v1,v2,rwave,parameter1,distance)
#----------------------------------------