Different intervals for Gauss-Legendre quadrature in numpy

依然范特西╮ 提交于 2019-12-01 04:23:57

To change the interval, translate the x values from [-1, 1] to [a, b] using, say,

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

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)

It prints:

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

quadpy (a little project of mine) as a simpler syntax for this:

import numpy
import quadpy

out = quadpy.line_segment.integrate(
    numpy.cos,
    [1.1, 1.2],  # the interval
    quadpy.line_segment.GaussLegendre(4)
    )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!