此脚本使用 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)
关于python - 这些对在 dblquad 中返回固定值的函数的频繁调用是否可以避免?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441614/