{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Fourier interpolation using FFT"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"%config InlineBackend.figure_format='svg'\n",
"\n",
"from numpy import pi,zeros,arange,exp,sin,abs,linspace,dot,outer,real,mod,log\n",
"from numpy import sqrt,sum\n",
"from numpy.fft import fft\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following function computes the trigonometric interpolant and plots it."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"# Wave numbers are arranged as k=[0,1,...,N/2,-N/2+1,-N/2,...,-1]\n",
"def fourier_interp(N,f,ne=500,fig=True):\n",
" if mod(N,2) != 0:\n",
" print(\"N must be even\")\n",
" return\n",
" h = 2*pi/N; x = h*arange(0,N);\n",
" v = f(x);\n",
" v_hat = fft(v)\n",
" k = zeros(N)\n",
" n = int(N/2)\n",
" k[0:n+1] = arange(0,n+1)\n",
" k[n+1:] = arange(-n+1,0,1)\n",
"\n",
" xx = linspace(0.0,2*pi,ne)\n",
" vf = real(dot(exp(1j*outer(xx,k)), v_hat)/N)\n",
" ve = f(xx)\n",
"\n",
" # Plot interpolant and exact function\n",
" if fig:\n",
" plt.plot(x,v,'o',xx,vf,xx,ve)\n",
" plt.legend(('Data','Fourier','Exact'))\n",
" plt.title(\"N = \"+str(N))\n",
"\n",
" errori = abs(vf-ve).max()\n",
" error2 = sqrt(h*sum((vf-ve)**2))\n",
" print(\"Error (max,L2) = \",errori,error2)\n",
" return errori, error2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Infintely smooth, periodic function"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error (max,L2) = 8.01581023779363e-14 4.559011236168057e-13\n"
]
},
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
"