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

标签 python python-2.7 scipy

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

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

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

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

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的定义,gfunhfun参数都是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/

相关文章:

python - Python 中的多个字符串插值

python - 如何使用 scipy 执行二维插值?

python - Matplotlib 所以日志轴在指定点只有次要刻度线标签。还可以更改颜色栏中刻度标签的大小

python - 来自 scipy.stats.rv_continuous 的自定义 PDF 不需要的上限

python - 如何在 Python 脚本中获取 Perl 脚本的结果?

python - 手动降低Python中的异常

python - 如何在 python 中过滤从 websocket api 接收的特定消息,并将其写入 CSV

python - 替换 pandas 列中满足某些条件的值会导致SettingWithCopyWarning

Python:解释器如何读取集合并查找交集

Python Koans 单例元组