Computational Methods for Data Analysis - Lecture 1

In [1]:
import scipy as sp
from numpy.fft import *
In [2]:
L = 20
n = 128
x = linspace(-L/2., L/2., n, endpoint=False)
In [3]:
u = exp(-x**2)
plot(x,u)
Out[3]:
[<matplotlib.lines.Line2D at 0x10f05e210>]
In [4]:
ut = fft(u)
plot(ut)
/Library/Python/2.7/site-packages/numpy-1.8.0.dev_4600b2f_20130131-py2.7-macosx-10.8-intel.egg/numpy/core/numeric.py:320: ComplexWarning: Casting complex values to real discards the imaginary part
  return array(a, dtype, copy=False, order=order)
Out[4]:
[<matplotlib.lines.Line2D at 0x10f0fc350>]
In [5]:
plot(abs(fftshift(ut)))
Out[5]:
[<matplotlib.lines.Line2D at 0x10f15a350>]
In [6]:
k = (2*pi/L)*r_[linspace(0, n/2-1, n/2), linspace(-n/2,-1,n/2)]
In [7]:
plot(fftshift(k), abs(fftshift(ut)))
Out[7]:
[<matplotlib.lines.Line2D at 0x10f1eac50>]

Derivatives

Formula for the derivative of a Fourier-transormed function:

$$\hat{f^{(n)}} = (ik)^n \hat{f}$$
In [8]:
sech = lambda x: 1./(np.cosh(x))
u = sech(x)
ut = fft(u)
# True first derivative
ud = -sech(x)*tanh(x)
# True second derivative
ud2 = sech(x)-2*sech(x)**3
In [9]:
plot(x, ud)
Out[9]:
[<matplotlib.lines.Line2D at 0x10f2dc2d0>]
In [10]:
# Estimated first derivative
ud_spect = ifft((1j*k)*ut)
# Estiamted second derivative
ud2_spect = ifft((1j*k)**2 * ut)
In [11]:
plot(x, ud)
plot(x,ud_spect,'r--')
Out[11]:
[<matplotlib.lines.Line2D at 0x10f2e3d90>]
In [12]:
plot(x, ud2)
plot(x, ud2_spect, 'r--')
Out[12]:
[<matplotlib.lines.Line2D at 0x10f2f81d0>]