{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# p02: Convergence of periodic spectral method"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We repeat program P1 using periodic spectral method to compute derivative of\n",
"\n",
"$$\n",
"u(x) = \\exp(\\sin(x)), \\qquad x \\in [-\\pi,\\pi]\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%config InlineBackend.figure_format='svg'\n",
"from scipy.linalg import toeplitz\n",
"from numpy import pi,arange,exp,sin,cos,zeros,tan,inf\n",
"from numpy.linalg import norm\n",
"from matplotlib.pyplot import figure,loglog,grid,xlabel,ylabel"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"figure()\n",
"for N in range(2,100,2):\n",
" h = 2.0*pi/N\n",
" x = -pi + arange(1,N+1)*h\n",
" u = exp(sin(x))\n",
" uprime = cos(x)*u # Exact derivative\n",
" col = zeros(N)\n",
" col[1:] = 0.5*(-1.0)**arange(1,N)/tan(arange(1,N)*h/2.0)\n",
" row = zeros(N); row[0] = col[0]; row[1:] = col[N-1:0:-1]\n",
" D = toeplitz(col,row)\n",
" error = norm(D.dot(u)-uprime,inf)\n",
" loglog(N,error,'or')\n",
" \n",
"grid(True); xlabel('N'); ylabel('error');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With about 24 points, the error is of order $10^{-12}$, compare this to the finite difference method in p01."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise\n",
"A Toepliz matrix is generated by its first column and first row. In the present case, we could also do\n",
"\n",
"```python\n",
"D = toeplitz(col, -col)\n",
"```"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.12.8"
}
},
"nbformat": 4,
"nbformat_minor": 4
}