This is how I tried to get the DFT of the unit pulse using numpy (the plot shows the unit pulse):
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
def plot_complex(space, arr):
plt.figure()
plt.plot(space, arr.real, label="real")
plt.plot(space, arr.imag, label="imag")
plt.legend(loc='upper left')
f = lambda x: 1 if abs(x) < 0.5 else 0
lo = -10
hi = 10
num_samples = 1000
sample_freq = num_samples/(hi-lo)
linspace = np.linspace(lo, hi, num_samples)
array = np.vectorize(f)(linspace)
coeff = np.fft.fft(array, num_samples)
# we need to shift the coefficients because otherwise negative frequencies are in the right half of the array
coeff_shifted = np.fft.fftshift(coeff)
plot_complex(linspace, array)
plt.title("The unit pulse")
This appears to be working, because using the inverse fft recovers the original unit pulse:
icoeff = np.fft.ifft(coeff)
plot_complex(linspace, icoeff)
plt.title("The recovered signal")
However, when looking at the signal, it doesn't look like the sinc function I would expect from looking at the continuous fourier transform:
freqspace = np.vectorize(lambda x: x * sample_freq)(np.fft.fftshift(np.fft.fftfreq(1000)))
plot_complex(freqspace, coeff_shifted)
plt.title("DFT coefficients")
plot_complex(freqspace[450:550], coeff_shifted[450:550])
plt.title("Zoomed in")
It only looks like the sinc function once every second coefficient is multiplied by -1:
# multiplies every second number in the array by -1
def flip_seconds(coeff):
return np.array([(1 if i%2 == 0 else -1) * s for (i,s) in enumerate(coeff)])
plot_complex(freqspace, flip_seconds(coeff_shifted))
Plot of the altered coefficients
Why is this?