The Home of Engineering and Sciences

Python FFT

Python_FFT

In Python, there are very mature FFT functions both in numpy and scipy. In this section, we will take a look of both packages and see how we can easily use .

This part of the code was written by my friend. I recommend his blog here:

Ding ding dong sunny

A very strong friend, friends who are interested can take a look.

Above code:

  1. import numpy as np
  2. from scipy.fftpack import fft
  3. def FFT(data,Fs):
  4. n=len(data)
  5. if n%2!=0:
  6. n-=1
  7. # data=data[range(0,n)] #由于要进行取半处理,所以将n与2取余
  8. data.pop()
  9. Y=fft(data) #快速傅里叶变换
  10. Fre=np.linspace(0,n-1,n)*Fs/n #linspace(start,stop,number)
  11. Fre=Fre[range(0,int(n/2))]
  12. Amp=np.abs(Y[range(0,int(n/2))])
  13. Amp=Amp/(n/2)
  14. Amp[0]=Amp[0]/2
  15. Amp[-1]=Amp[-1]/2
  16. return Fre, Amp

There are not many code comments, so I will add some text to explain:

The first parameter is the sampling value of the waveform function of Fourier analysis, and the second parameter is the number of sampling points per unit time, which refers to how many points of data are sampled in one second.

For example:

I gave 100 points for two cycles, so one cycle is 50 points. Assuming one cycle is 10 seconds, then 10 seconds corresponds to 50 points, 1 second is 5 points, one cycle is 10 seconds, the fundamental frequency is 0.1, so if only harmonics are analyzed, it is 0.3, 0.5, 0.7, etc. In this way, the corresponding fundamental wave, third harmonic, and fifth harmonic can all be obtained.

Attach the example and drawing code:

  1. func1=func[:76] #取两个周期的点
  2. F,A=FFT(func1,38)
  3. plt.bar(F,A,width=0.4)
  4. x=range(0,15,1)
  5. plt.xlim(0,15)
  6. plt.xticks(x)
  7. plt.xlabel(‘Harmonic order’)
  8. plt.ylabel(‘Amplitude’)

Python_FFT

 The decomposed result looks like the one above.

Finally, a few more words. Since FFT processing requires the use of all the data of the waveform, if the original data contains abnormal data such as nan, FFT will not produce any results during processing. Pay attention to the cleaning of the original data.

Exit mobile version