Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中实现复合高斯求积_Python_Numerical Methods - Fatal编程技术网

在Python中实现复合高斯求积

在Python中实现复合高斯求积,python,numerical-methods,Python,Numerical Methods,我想在Python中实现复合高斯求积来计算积分∫01 ex2 dx。使用Python的quad命令进行评估,我得到∫01 ex2 dx≈ 1.46 下面是我在Python中实现这一点的尝试。我所期望的是,随着n变大,求积越接近“实”积分。然而,当我改变n时,结果变得越来越小。我犯了什么错误 def gauss(f,a,b,n): h = float(b-a)/n [x,w] = np.polynomial.legendre.leggauss(n) result = 0

我想在Python中实现复合高斯求积来计算积分∫01 ex2 dx。使用Python的quad命令进行评估,我得到∫01 ex2 dx≈ 1.46

下面是我在Python中实现这一点的尝试。我所期望的是,随着n变大,求积越接近“实”积分。然而,当我改变n时,结果变得越来越小。我犯了什么错误

def gauss(f,a,b,n):
    h = float(b-a)/n
    [x,w] = np.polynomial.legendre.leggauss(n)
    result =  0
    for i in range(n):
        result += w[i] * f(x[i])
    result *= h
    return result


    for i in range(1,10):  
        print(gauss(exp,0,1,i))
    
    2.0
    1.3956124250860895
    0.9711551112557443
    0.731135234765899
    0.5850529284514102
    0.4875503086966867
    0.41790049038666144
    0.36566293624426005
    0.32503372130693325

以下是基于您的尝试的工作代码:

import numpy as np

def gauss(f,a,b,n):
    half = float(b-a)/2.
    mid = (a+b)/2.
    [x,w] = np.polynomial.legendre.leggauss(n)
    result =  0.
    for i in range(n):
        result += w[i] * f(half*x[i] + mid)
    result *= half
    return result

def fun(x):
    return np.exp(x**2)

for i in range(1,10):  
    print(gauss(fun,0,1,i))
问题是,积分必须重新缩放到您正在使用的勒让德多项式的域。此外,您没有正确使用求积规则(它没有使用代码中的步长h) 正确的规则是:

∫ab f(x)dx≈ (b-a)/2∑i=1nwif((b-a)/2ξi+(a+b)/2)

通过此操作,上述代码输出:

1.2840254166877414
1.4541678892391303
1.462409711477322
1.462646815656646
1.4626516680186825
1.4626517449041974
1.4626517458962964
1.4626517459070796
1.462651745907181