In [1]:
import numpy
from matplotlib import pyplot
% matplotlib inline
In [2]:
import os, sys
sys.path.append(os.path.split(os.path.split(os.getcwd())[0])[0])
In [3]:
import utils.quadrature as quad
Let $f = x^6$. And $\int_{-1}^{1} f dx = \frac{2}{7}$.
Use Gauss-Lobatto-Legendre quadrature to numerically evaluate $\int_{-1}^{1} f dx$ with number of quadrature points $Q=4,\ 5,\ 6$.
In [4]:
def f(x):
"""the integrand: x**6"""
return x**6
In [5]:
print("The exact solution is: ", 2./7.)
for Qi in [4, 5, 6]:
qd = quad.GaussLobattoJacobi(Qi)
ans = qd(f, -1, 1)
print("Q = {0}, ans = {1}, absolute error is {2}".format(Qi, ans, abs(ans-2./7.)))
Let $f = x^6$. And $\int_{-1}^{2} f dx = \frac{129}{7}$.
Use Gauss-Lobatto-Legendre quadrature to numerically evaluate $\int_{-1}^{2} f dx$ with number of quadrature points $Q=4,\ 5,\ 6$.
In [6]:
print("The exact solution is: ", 129./7.)
for Qi in [4, 5, 6]:
qd = quad.GaussLobattoJacobi(Qi)
ans = qd(f, -1, 2)
print("Q = {0}, ans = {1}, absolute error is {2}".format(Qi, ans, abs(ans-129./7.)))
Let $f = \sin{x}$. And $\int_{0}^{\pi/2} f dx = 1$.
Use Gauss-Lobatto-Legendre quadrature to numerically evaluate $\int_{0}^{\pi/2} f dx$ with number of quadrature points $2 \le Q \le 8$ and plot the error to check the convergence order.
In [7]:
def f(x):
"""the integrand: x**6"""
return numpy.sin(x)
In [8]:
print("The exact solution is: ", 1.)
Q = range(2, 9)
err = numpy.zeros_like(Q, dtype=numpy.float64)
for i, Qi in enumerate(Q):
qd = quad.GaussLobattoJacobi(Qi)
ans = qd(f, 0., numpy.pi/2.)
err[i] = numpy.abs(ans - 1.)
print("Q = {0}, ans = {1}, absolute error is {2}".format(Qi, ans, err[i]))
In [9]:
pyplot.semilogy(Q, err, 'k.-', lw=2, markersize=15)
pyplot.title(r"Error of numerical integration of $\int_{0}^{\pi/2}\sin{(x)} dx$" +
"\n with Gauss-Lobatto-Legendre quadrature", y=1.08)
pyplot.xlabel(r"$Q$" + ", number of quadratiure points")
pyplot.ylabel("absolute error")
pyplot.grid();