我已经使用 Area、sigmax 和 sigmay 参数定义了二维高斯分布(独立变量之间没有相关性)。 当我在两个变量中从 (-inf, inf) 进行积分时,我只会在 sigmax 和 sigmay 为 1 时获得面积。
import numpy as np
import scipy.integrate as sci
class BeamDistribution(object):
def __init__(self, Ipeak, sigmax, sigmay):
print Ipeak, sigmax, sigmay
self.__Ipeak = Ipeak
self.__sigmax = sigmax
self.__sigmay = sigmay
def value(self, x, y):
factor = self.__Ipeak/(2.*np.pi*self.__sigmax * self.__sigmay)
factorx = np.exp(-x**2/(2.*self.__sigmax**2))
factory = np.exp(-y**2/(2.*self.__sigmay**2))
return factor*factorx*factory
def integral(self, a, b, c, d):
integration = sci.dblquad(self.value, a, b, lambda x: c, lambda x: d,
epsrel = 1e-9, epsabs = 0)
# sci.quad_explain()
return integration
def __call__(self, x, y):
return self.value(x, y)
if __name__ == "__main__":
Ipeak = 65.0e-3
sigmax = 0.2e-3
sigmay = 0.3e-3
limit = np.inf
my_beam_class = BeamDistribution(Ipeak, sigmax, sigmay)
total = my_beam_class.integral(-limit, limit, -limit, limit)
print "Integrated total current ",total," of Ipeak ", Ipeak
my_beam_class = BeamDistribution(Ipeak, 1, 1)
total = my_beam_class.integral(-limit, limit, -limit, limit)
print "Integrated total current ",total," of Ipeak ", Ipeak
输出是
0.065 0.0002 0.0003
Integrated total current (7.452488478001055e-32, 6.855160478762106e-41) of Ipeak 0.065
0.065 1 1
Integrated total current (0.4084070449667172, 1.0138233535120856e-11) of Ipeak 0.065
知道为什么会这样吗?我想它应该很简单,但经过数小时的查看,我看不出有什么问题。
请您参考如下方法:
集成高斯核的正确方法是使用 Gauss-Hermite 正交,参见 here
它在 Python 中作为 SciPy 模块实现 http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.polynomial.hermite.hermgauss.html
代码,高斯核积分应该是√(π)
import math
import numpy as np
a,w = np.polynomial.hermite.hermgauss(32)
print(a)
print(w)
def f(x):
return 1.0
s = 0.0
for k in range(0,len(a)):
s += w[k]*f(a[k])
print(s - math.sqrt(math.pi))
二维案例
Ipeak = 0.065
sigmax = 0.2e-3
sigmay = 0.3e-3
sqrt2 = math.sqrt(2.)
def h(x, y):
return Ipeak*1.0/math.pi
s = 0.0
for k in range(0, len(a)):
x = sqrt2 * sigmax * a[k]
t = 0.0
for l in range(0, len(a)):
y = sqrt2 * sigmay * a[l]
t += w[l] * h(x, y)
s += w[k]*t
print(s)
