Skip to main content
 首页 » 编程设计

python之这些频繁调用在 dblquad 中返回固定值的函数是否可以避免

2024年09月07日8exmyth

此脚本使用 SciPy 的 dblquad 计算来自均匀带电环的 (x0, y0, z0) 处的电场.

我的问题是关于 gfun 和 hfun 的使用,它们定义了内部积分限制对外部积分变量的函数依赖性。如果我选择在笛卡尔坐标系中积分,这将是千篇一律的形状,但当我使用圆柱坐标系时,函数返回常量 float 。

有没有办法消除这些只返回常量的函数调用,以避免函数调用的时间损失?

该示例可能没有在其他方面进行优化,但它只是一个简单的示例,用于展示 gfun 和 hfun 的使用。

def Excalc(r, th): 
    x, y, z = r*np.cos(th), r*np.sin(th), 0.0 
    return (x0-x) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5 
 
def Eycalc(r, th): 
    x, y, z = r*np.cos(th), r*np.sin(th), 0.0 
    return (y0-y) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5 
 
def Ezcalc(r, th): 
    x, y, z = r*np.cos(th), r*np.sin(th), 0.0 
    return (z0-z) * ((x0-x)**2 + (y0-y)**2 + (z0-z)**2)**-1.5 
 
def gfun(x): 
    return rmin 
 
def hfun(x): 
    return rmax 
 
import numpy as np 
import matplotlib.pyplot as plt 
from scipy.integrate import dblquad 
 
twopi = 2.*np.pi 
 
# annulus of uniform, unit charge density 
rmin, rmax   = 0.8, 1.2 
thmin, thmax = 0,   twopi 
 
# point to evaluate the field 
x0, y0, z0 = 1.5, 0, 1   
 
eps = 1E-10 
 
Ex, Exerr  = dblquad(Excalc, thmin, thmax, gfun, hfun, epsrel=eps) 
Ey, Eyerr  = dblquad(Eycalc, thmin, thmax, gfun, hfun, epsrel=eps) 
Ez, Ezerr  = dblquad(Ezcalc, thmin, thmax, gfun, hfun, epsrel=eps) 
 
print Ex, Ey, Ez 
print Exerr, Eyerr, Ezerr 

请您参考如下方法:

根据dblquad的定义,gfun和hfun参数都是callable类型,也就是说它们将被 dblquad 以函数调用的方式调用。

不过,您可以通过使用 Python 的 lambda 而不是普通函数来使代码更简洁一些。示例:

Ex, Exerr = dblquad(Excalc, thmin, thmax, lambda: 0.8, lambda: 1.2, epsrel=eps)