阶数$n$ | 零点$x_i$ | 求积系数$A_i$ |
1 | $0$ | $2$ |
2 | $\pm \sqrt{1 / 3}$ | $1$ |
3 | $\pm \sqrt{3 / 5}$ $0$ |
$5 / 9$ $8 / 9$ |
6 | $\pm 0.238619186081526$ $\pm 0.661209386472165$ $\pm 0.932469514199394$ |
$0.467913934574257$ $0.360761573028128$ $0.171324492415988$ |
10 | $\pm 0.973906528517240$ $\pm 0.433395394129334$ $\pm 0.865063366688893$ $\pm 0.148874338981367$ $\pm 0.679409568299053$ |
$0.066671344307672$ $0.269266719309847$ $0.149451349151147$ $0.295524224714896$ $0.219086362515885$ |
1 # Gauss-Legendre Quadrature之实现 2 3 import numpy 4 5 6 def getGaussParams(num=6): 7 if num == 1: 8 X = numpy.array([0]) 9 A = numpy.array([2]) 10 elif num == 2: 11 X = numpy.array([numpy.math.sqrt(1/3), -numpy.math.sqrt(1/3)]) 12 A = numpy.array([1, 1]) 13 elif num == 3: 14 X = numpy.array([numpy.math.sqrt(3/5), -numpy.math.sqrt(3/5), 0]) 15 A = numpy.array([5/9, 5/9, 8/9]) 16 elif num == 6: 17 X = numpy.array([0.238619186081526, -0.238619186081526, 0.661209386472165, -0.661209386472165, 0.932469514199394, -0.932469514199394]) 18 A = numpy.array([0.467913934574257, 0.467913934574257, 0.360761573028128, 0.360761573028128, 0.171324492415988, 0.171324492415988]) 19 elif num == 10: 20 X = numpy.array([0.973906528517240, -0.973906528517240, 0.433395394129334, -0.433395394129334, 0.865063366688893, -0.865063366688893, 21 0.148874338981367, -0.148874338981367, 0.679409568299053, -0.679409568299053]) 22 A = numpy.array([0.066671344307672, 0.066671344307672, 0.269266719309847, 0.269266719309847, 0.149451349151147, 0.149451349151147, 23 0.295524224714896, 0.295524224714896, 0.219086362515885, 0.219086362515885]) 24 else: 25 raise Exception(">>> Unsupported num = {} <<<".format(num)) 26 return X, A 27 28 29 def getGaussQuadrature(func, a, b, X, A): 30 ‘‘‘ 31 func: 原始被积函数 32 a: 积分区间下边界 33 b: 积分区间上边界 34 X: 求积节点数组 35 A: 求积系数数组 36 ‘‘‘ 37 term1 = (b - a) / 2 38 term2 = (a + b) / 2 39 term3 = func(term1 * X + term2) 40 term4 = numpy.sum(A * term3) 41 val = term1 * term4 42 return val 43 44 45 def testFunc(x): 46 val = x ** 2 * numpy.exp(x) 47 return val 48 49 50 51 if __name__ == "__main__": 52 X, A = getGaussParams(10) 53 a, b = 0, 1 54 numerSol = getGaussQuadrature(testFunc, 0, 1, X, A) 55 exactSol = numpy.e - 2 56 relatErr = (exactSol - numerSol) / exactSol 57 print("numerical: {}; exact: {}; relative error: {}".format(numerSol, exactSol, relatErr))
阶数$n$ | numerical integral | exact integral | relative error |
1 | $0.412180317675032$ | $0.718281828459045$ | $0.4261579489497921$ |
2 | $0.711941774242270$ | $0.718281828459045$ | $0.008826694433265773$ |
3 | $0.718251779040964$ | $0.718281828459045$ | $4.1835136140953615e-05$ |
6 | $0.718281828489842$ | $0.718281828459045$ | $-4.2875662903868903e-11$ |
10 | $0.718281828458231$ | $0.718281828459045$ | $1.1338997850082094e-12$ |
Gauss-Legendre Quadrature - Python实现
原文:https://www.cnblogs.com/xxhbdk/p/14203877.html