{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# p05: Repetition of p04 via FFT"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%config InlineBackend.figure_format='svg'\n",
"# For complex v, delete \"real\" commands.\n",
"from numpy import pi,inf,linspace,maximum,abs,zeros,arange,real,sin,cos,exp\n",
"from numpy.fft import fft,ifft\n",
"from numpy.linalg import norm\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",
"\n",
"# wave numbers\n",
"ik = 1j*zeros(N)\n",
"ik[0:N//2+1] = 1j*arange(0,N//2+1)\n",
"ik[N//2+1:] = 1j*arange(-N//2+1,0,1)\n",
"\n",
"# Differentiation of a hat function:\n",
"v = maximum(0.0,1.0-abs(x-pi)/2.0)\n",
"v_hat = fft(v)\n",
"w_hat = ik * v_hat; w_hat[N//2] = 0.0\n",
"w = real(ifft(w_hat))\n",
"\n",
"figure(figsize=(10,6))\n",
"\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,w,'.-')\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",
"v_hat = fft(v)\n",
"w_hat = ik * v_hat; w_hat[N//2] = 0.0\n",
"w = real(ifft(w_hat))\n",
"\n",
"subplot(3,2,3)\n",
"plot(x,v,'.-')\n",
"axis([0, 2*pi, 0, 3])\n",
"subplot(3,2,4)\n",
"plot(x,w,'.-')\n",
"axis([0, 2*pi, -2, 2])\n",
"error = norm(w-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
}