{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Gauss quadrature of sqrt(x-0.5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us compute\n",
"$$\n",
"\\int_0^1 \\sqrt{|x-1/2|} dx = \\frac{\\sqrt{2}}{3}\n",
"$$\n",
"We will compute this with Gauss-Legendre quadrature and also by breaking it into two parts\n",
"$$\n",
"\\int_0^{1/2} \\sqrt{|x-1/2|} dx + \\int_{1/2}^1 \\sqrt{|x-1/2|} dx\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 2 6.588045e-02 0.0000e+00 2.859548e-02 0.0000e+00\n",
" 4 2.572864e-02 2.5606e+00 5.105786e-03 5.6006e+00\n",
" 8 9.738642e-03 2.6419e+00 8.209359e-04 6.2195e+00\n",
" 16 3.583266e-03 2.7178e+00 1.194398e-04 6.8732e+00\n",
" 32 1.294540e-03 2.7680e+00 1.623859e-05 7.3553e+00\n",
" 64 4.628656e-04 2.7968e+00 2.121816e-06 7.6532e+00\n",
" 128 1.645897e-04 2.8122e+00 2.713392e-07 7.8198e+00\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.sqrt(np.abs(x-0.5))\n",
"a,b = 0.0,1.0\n",
"c = 0.5*(a+b)\n",
"qe = np.sqrt(2.0)/3.0 # Exact integral\n",
"\n",
"n,N = 2,7\n",
"err1,err2,nodes = np.zeros(N),np.zeros(N),np.zeros(N)\n",
"for i in range(N):\n",
" nodes[i] = n\n",
" val = fixed_quad(f,a,b,n=n)\n",
" err1[i] = np.abs(val[0]-qe)\n",
" val = fixed_quad(f,a,c,n=n/2) + fixed_quad(f,c,b,n=n/2)\n",
" err2[i] = np.abs(val[0]+val[2]-qe)\n",
" if i>0:\n",
" print('%5d %14.6e %12.4e %14.6e %12.4e' % \n",
" (n,err1[i],err1[i-1]/err1[i],err2[i],err2[i-1]/err2[i]))\n",
" else:\n",
" print('%5d %14.6e %12.4e %14.6e %12.4e' % (n,err1[i],0,err2[i],0))\n",
" n = 2*n\n",
"\n",
"plt.figure()\n",
"plt.loglog(nodes,err1,'o-',nodes,err2,'s-')\n",
"plt.xlabel('n')\n",
"plt.ylabel('Error')\n",
"plt.legend(('Gauss','Gauss+Gauss'));"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}