numpy中高斯-勒让德正交的不同间隔 [英] Different intervals for Gauss-Legendre quadrature in numpy

查看:182
本文介绍了numpy中高斯-勒让德正交的不同间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can we use the NumPy package numpy.polynomial.legendre.leggauss over intervals other than [-1, 1]?

以下示例比较了 到间隔[-1, 1]的高斯-勒根德方法.

The following example compares scipy.integrate.quad to the Gauss-Legendre method over the interval [-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

推荐答案

更改时间间隔,使用例如

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

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

and then scale the quadrature formula by (b - a)/2:

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

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

Here's a modified version of your example:

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-14
Gauss-Legendre solution: 1.0
Difference between QUADPACK and Gauss-Legendre:  4.62963001269e-14

这篇关于numpy中高斯-勒让德正交的不同间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆