[英]How to find frequency of a square wave using FFT
In the FFT (second) plot, I am expecting a bigger peak at frequency = 1.0, compared to other frequencies, since it is a 1 Hz Square Wave signal sampled at 5Hz. 在FFT(第二个)图中,与其他频率相比,我期望在频率= 1.0处有一个更大的峰值,因为它是在5Hz采样的1Hz方波信号。
I am a beginner at this, possibly missing something silly here Here's what I have done: 我是一个初学者,可能在这里错过了一些愚蠢的事情。
import numpy as np
from matplotlib import pyplot as plt
from scipy import signal
t500 = np.linspace(0,5,500,endpoint=False)
s1t500 = signal.square(2*np.pi*1.0*t500)
First plot shows 1 Hz Square Wave sampled at 5Hz for 5 seconds: 第一个图显示了以5Hz采样5秒钟的1 Hz方波:
t5 = np.linspace(0,5,25,endpoint=False)
t5 = t5 + 1e-14
s1t5 = signal.square(2.0*np.pi*1.0*t5)
plt.ylim(-2,2); plt.plot(t500,s1t500,'k',t5,s1t5,'b',t5,s1t5,'bo'); plt.show()
Here in the Second plot, I am expecting the magnitude at f=1 Hz to be more than at f=2. 在第二张图中,我期望f = 1 Hz时的幅度大于f = 2时的幅度。 Am I missing something ? 我想念什么吗?
y1t5 = np.fft.fft(s1t5)
ff1t5 = np.fft.fftfreq(25,d=0.2)
plt.plot(ff1t5,y1t5); plt.show()
It seems you missed the fact that Fourier transform produces functions (or sequences of numbers in case of DFT/FFT) in complex space: 似乎您错过了以下事实:傅立叶变换会在复杂空间中生成函数(或在DFT / FFT情况下为数字序列):
>>> np.fft.fft(s1t5)
[ 5. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j
5.-15.38841769j 0. +0.j 0. +0.j 0. +0.j 0. +0.j
5. +3.63271264j 0. +0.j 0. +0.j 0. +0.j 0. +0.j
# and so on
In order to see the amplitude spectrum on your plot, apply np.absolute
or abs
: 为了查看曲线图上的振幅频谱,请应用np.absolute
或abs
:
>>> np.absolute(np.fft.fft(s1t5))
[ 5. 0. 0. 0. 0. 16.18033989
0. 0. 0. 0. 6.18033989 0. 0.
0. 0. 6.18033989 0. 0. 0. 0.
16.18033989 0. 0. 0. 0. ]
Otherwise only real part will be shown. 否则,将仅显示实部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.