Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different intervals for Gauss-Legendre quadrature in numpy

How can we use the NumPy package numpy.polynomial.legendre.leggauss over intervals other than [-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)

Output:

The QUADPACK solution: 1.68294196962 with error: 1.86844092378e-14
Gauss-Legendre solution: 1.68294196961
Difference between QUADPACK and Gauss-Legendre:  1.51301193796e-12
like image 206
Paul Avatar asked Oct 31 '15 23:10

Paul


1 Answers

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
like image 63
Warren Weckesser Avatar answered Oct 21 '22 04:10

Warren Weckesser