我是 python 的新手,正在尝试对函数进行数值积分。一切似乎都有效,但我得到的结果与我在 Mathematica 中得到的结果有很大不同(我知道这是正确的)。有人可以帮我弄清楚发生了什么事吗?
这是代码:
def integrand(x, d, a, b, l, s, wavelength, y):
return b*(np.sinc((np.pi*a/(wavelength*s))*(y + s*b*x/l))**2)*np.cos((np.pi*d/(wavelength*s))*(y + s*b*x/l))**2
def intensity(y):
result, error = si.quad(integrand, -1/2, 1/2, epsrel = 1e-16, epsabs = 1e-16,
args=(0.0006, 0.000150, 0.000164, 0.8, 1.06, 0.0000006328, y))
return result
例如,如果我计算强度(0),我在Python中得到0.0001580120220796804,在Mathematica中得到0.000158898。在 0.5% 之内,所以看起来还可以。但是如果我计算强度(0.001),我在Python中得到1.8729902318383768e-05,在Mathematica中得到0.00012034,它们相差了近一个数量级。请注意,我已尝试减少绝对和相对误差,但这没有任何效果。
如有任何帮助,我们将不胜感激。
这是 Mathematica 代码:
NumInt[d_, a_, b_, l_, s_, lambda_, y_] := NIntegrate[b Sinc[(a Pi/(s lambda)) (y - (s*b*
x/l))]^2 Cos[(d Pi/(s lambda)) (y - (s*b*x/l))]^2, {x, -1/2,
1/2}]
然后
NumInt[0.0006, 0.000150, 0.000164, 0.8, 1.06, 0.0000006328, 0.001]
numpy.sinc
定义为 sin(pi*x)/(pi*x)
。 Mathematica 的 Sinc
函数不包含 pi
因子。要修复此差异,请从 Python 代码中的 np.pi
参数中删除 sinc()
。当我进行更改时,我得到了与 Mathematica 一致的结果(我修改了 intensity()
也返回了 quad
返回的错误):
In [12]: intensity(0)
Out[12]: (0.00015889773970382816, 1.764119291800849e-18)
In [13]: intensity(0.001)
Out[13]: (0.00012034021042092513, 1.3360447239754727e-18)