This notebook is part of a lecture I gave in my DSP class on Halloween, Oct 31. I'll clean it up later, but need to post it (even in its current minimalist condition) for my students.
%pylab inline
from scipy.fftpack import fft, ifft
x = array([1,-1,1,-1])
fft(x)
fft(x,n=8)
xz = r_[x,zeros(4)]
xz
fft(xz)
c_[x,zeros(4)]
y = fft(x)
xhat = ifft(y)
x-xhat
x2 = rand(1024*1024)
y2 = fft(x2)
x2hat = ifft(y2)
r = x2-x2hat
r[:10]
max(abs(x2-x2hat))
x2hat[:10]
real(x2hat)[:10]
#x = array([0,0,0,1,0,0,0,0]) + 1j*array([0,0,0,0,0,0,0,0])
x = exp(1j*2.1*2*pi*arange(8)/8)
y = fft(x)
subplot(1,2,1)
stem(real(y))
subplot(1,2,2)
stem(imag(y))
xlim([0,8])
N=64
omega = 2.3*2*pi/N
n = arange(N)
x = cos(omega*n)
y = fft(x)
stem(abs(y))
N=256
sigma = 1.0
omega = 2*pi*35.5/N
omega2 = 2*pi*44/N
#x = exp(omega*1j*arange(N))
x = cos(omega*arange(N))+2*cos(omega2*arange(N))
x += sigma*randn(N)
y = fft(x)
plot(abs(y))
plot(x)
from scipy.signal import kaiser
window = kaiser(N,beta=14)
plot(abs(fft(x*window)))
plot(abs(fft(window)))
plot(window)
The Dirichlet kernel is the discrete time version of the sinc function. For some reason, it gets little of the acclaim of the sinc function. I've even seen textbooks incorrectly use the sinc function when they should be using the Dirichlet function. Even the Wikipedia entry for the sinc function make no mention of the Dirichlet kernel.
The first version uses the piecewise function to take care of the division by 0 problem. However, as written it doesn't work for x being any other integer except 0. I suppose it could be improved, but Dirichlet2 solves the problem a different (and arguably better) way: it allows numpy to compute nan's, then replaced the nan's by the correct limit.
def dirichlet(x,N):
return piecewise(x, [x==0, x != 0], [N, lambda x: sin(N*pi*x)/sin(pi*x)])
x = linspace(-0.5,0.5,201)
plot(x,abs(dirichlet(x,16)))
def dirichlet2(x,N):
seterr(divide='ignore')
y = sin(N*pi*x)/sin(pi*x)
y[isnan(y)] = N
return y
plot(abs(dirichlet2(linspace(-0.5,0.5,201),16)))