{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# p04: Periodic spectral differentiation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We compute derivatives of following periodic functions on finite interval\n",
"\n",
"$$\n",
"v(x) = \\max(0, 1-|x-\\pi|/2), \\qquad x \\in [0,2\\pi]\n",
"$$\n",
"\n",
"and\n",
"\n",
"$$\n",
"v(x) = \\exp(\\sin(x)), \\qquad x \\in [0,2\\pi]\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%config InlineBackend.figure_format='svg'\n",
"from numpy import pi,inf,linspace,zeros,arange,sin,cos,tan,exp,maximum,abs\n",
"from numpy.linalg import norm\n",
"from scipy.linalg import toeplitz\n",
"from matplotlib.pyplot import figure,subplot,plot,axis,title,text"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Set up grid and differentiation matrix:\n",
"N = 24; h = 2*pi/N; x = h*arange(1,N+1);\n",
"col = zeros(N)\n",
"col[1:] = 0.5*(-1.0)**arange(1,N)/tan(arange(1,N)*h/2.0)\n",
"D = toeplitz(col,-col)\n",
"\n",
"figure(figsize=(10,6))\n",
"\n",
"# Differentiation of a hat function:\n",
"v = maximum(0,1-abs(x-pi)/2)\n",
"subplot(3,2,1)\n",
"plot(x,v,'.-')\n",
"axis([0, 2*pi, -.5, 1.5])\n",
"title('function')\n",
"subplot(3,2,2)\n",
"plot(x,D.dot(v),'.-')\n",
"axis([0, 2*pi, -1, 1])\n",
"title('spectral derivative')\n",
"\n",
"# Differentiation of exp(sin(x)):\n",
"v = exp(sin(x)); vprime = cos(x)*v;\n",
"subplot(3,2,3)\n",
"plot(x,v,'.-')\n",
"axis([0, 2*pi, 0, 3])\n",
"subplot(3,2,4)\n",
"plot(x,D.dot(v),'.-')\n",
"axis([0, 2*pi, -2, 2])\n",
"error = norm(D.dot(v)-vprime,inf)\n",
"text(1.5,1.4,\"max error=\"+str(error));"
]
}
],
"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
}