{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Gauss quadrature using Scipy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will compute\n",
"$$\n",
"\\int_0^\\pi \\exp(x)\\cos(x) dx\n",
"$$\n",
"using Gauss-Legendre quadrature."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 2 2.65864149305591e-01\n",
" 3 5.70741337850613e-02\n",
" 4 1.56826095079055e-04\n",
" 5 1.77805009098364e-05\n",
" 6 1.47122865001847e-08\n",
" 7 1.14247988847183e-09\n",
" 8 4.15667500419659e-13\n",
" 9 2.84217094304040e-14\n"
]
},
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'svg'\n",
"from scipy.integrate import fixed_quad\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"f = lambda x: np.exp(x)*np.cos(x)\n",
"a,b = 0.0,np.pi\n",
"qe = -0.5*(1.0 + np.exp(np.pi)) # Exact integral\n",
"\n",
"N = np.arange(2,10)\n",
"err = np.zeros(len(N))\n",
"for (i,n) in enumerate(N):\n",
" val = fixed_quad(f,a,b,n=n)\n",
" err[i] = np.abs(val[0]-qe)\n",
" print('%5d %24.14e' % (n,err[i]))\n",
"\n",
"plt.figure()\n",
"plt.semilogy(N,err,'o-')\n",
"plt.xlabel('n')\n",
"plt.ylabel('Error');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The error plot indicates exponential convergence."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [default]",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}