gpt4 book ai didi

python - numpy中Gauss-Legendre正交的不同间隔

转载 作者:太空狗 更新时间:2023-10-29 22:29:45 24 4
gpt4 key购买 nike

我们如何使用 NumPy 包 numpy.polynomial.legendre.leggauss[-1, 1] 以外的时间间隔内?


下面的例子比较了scipy.integrate.quad[-1, 1] 区间内的 Gauss-Legendre 方法。

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

最佳答案

收件人change the interval ,将 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)

它打印:

The QUADPACK solution: 1.0 with error: 1.11022302463e-14Gauss-Legendre solution: 1.0Difference between QUADPACK and Gauss-Legendre:  4.62963001269e-14

关于python - numpy中Gauss-Legendre正交的不同间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33457880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com