Reputation: 729
I am implementing a DFT and transformed a sine wave (f = 440 Hz) as test. However there is a peak in the transformed signal where I don't expect one (see figure below). Can someone see why it is there?
My code:
import numpy as np
import matplotlib.pyplot as plt
t = 0.1
freq = 440
Fs = 2000
T = 1/Fs
N = int(Fs * t)
# signal information
omega = 2 * np.pi * freq # angular frequency of the sine wave
t_vec = np.arange(N) * T # time vector for plotting
y = np.sin(omega * t_vec) # sine input signal
def DFT(y, N):
dft = []
angle = (-1 * 1j * 2 * np.pi) / (N)
for k in range(int(N)):
X = 0
for n in range(int(N)):
X += y[n] * np.exp(angle * k * n)
dft.append(X)
return dft
freq_vec = Fs * np.arange((N))/N
dft_signal = np.abs(DFT(y = y, N = N))
#Plots
fig, (ax1, ax2) = plt.subplots(2)
ax1.plot(t_vec, y, label='$y = numbers')
ax1.set(ylabel='Amplitude', xlabel='Time [s]', title = 'Input Signal')
ax2.plot(freq_vec, dft_signal, linewidth=5)
ax2.set(yscale='log', xscale='log', ylabel='Amplitude', xlabel='Frequency [Hz]', title = 'DFT of Input Signal')
plt.tight_layout()
plt.show()
Upvotes: 0
Views: 214
Reputation: 407
Your code seems good to me. What you see are simply the negative frequencies since the Fourier Transform of a sine function is made of a peak in the positive frequencies and one peak in the negative. Don't plot it in xlog scale and it will appear more obvious! Then it is just a matter of fftshift
to put the zero frequency in the middle or at the beginning of the array (like your implementation).
Remember that if your frequency range is Fs
your DFT only goes from -Fs/2
to +Fs/2
Upvotes: 1