numpy中高斯-勒让德正交的不同间隔

发布于 2021-01-29 16:23:22

我们如何numpy.polynomial.legendre.leggauss在非间隔内使用NumPy包[-1, 1]


下面的示例比较scipy.integrate.quad了整个时间间隔内的Gauss-
Legendre方法[-1, 1]

import numpy as np
from scipy import integrate

# Define function and interval
a = -1.
b =  1.
f = lambda x: np.cos(x)

# Gauss-Legendre (default interval is [-1, 1])
deg = 6
x, w = np.polynomial.legendre.leggauss(deg)
gauss = sum(w * f(x))

# For comparison
quad, quad_err = integrate.quad(f, a, b)

print 'The QUADPACK solution: {0:.12} with error: {1:.12}'.format(quad, quad_err)
print 'Gauss-Legendre solution: {0:.12}'.format(gauss)
print 'Difference between QUADPACK and Gauss-Legendre: ', abs(gauss - quad)

输出:

The QUADPACK solution: 1.68294196962 with error: 1.86844092378e-14
Gauss-Legendre solution: 1.68294196961
Difference between QUADPACK and Gauss-Legendre:  1.51301193796e-12
关注者
0
被浏览
52
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    更改间隔,请使用以下方法将x值从[-1,1]转换为[a,b]:

    t = 0.5*(x + 1)*(b - a) + a
    

    然后将正交公式缩放为(b-a)/ 2:

    gauss = sum(w * f(t)) * 0.5*(b - a)
    

    这是您的示例的修改版本:

    import numpy as np
    from scipy import integrate
    
    # Define function and interval
    a = 0.0
    b = np.pi/2
    f = lambda x: np.cos(x)
    
    # Gauss-Legendre (default interval is [-1, 1])
    deg = 6
    x, w = np.polynomial.legendre.leggauss(deg)
    # Translate x values from the interval [-1, 1] to [a, b]
    t = 0.5*(x + 1)*(b - a) + a
    gauss = sum(w * f(t)) * 0.5*(b - a)
    
    # For comparison
    quad, quad_err = integrate.quad(f, a, b)
    
    print 'The QUADPACK solution: {0:.12} with error: {1:.12}'.format(quad, quad_err)
    print 'Gauss-Legendre solution: {0:.12}'.format(gauss)
    print 'Difference between QUADPACK and Gauss-Legendre: ', abs(gauss - quad)
    

    它打印:

    QUADPACK解决方案:1.0,错误:1.11022302463e-14
    高斯-勒根德雷解决方案:1.0
    QUADPACK和Gauss-Legendre之间的差异:4.62963001269e-14
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看