Skip to content

Instantly share code, notes, and snippets.

@huailiang
Last active December 14, 2019 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huailiang/45ccce613e77ce860d4e161ee1ca90fe to your computer and use it in GitHub Desktop.
Save huailiang/45ccce613e77ce860d4e161ee1ca90fe to your computer and use it in GitHub Desktop.
fft 傅里叶变换
import numpy as np
from scipy.fftpack import fft, ifft
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 800)
# 设置需要采样的信号,频率分量有80,190和300
y = 7 * np.sin(2 * np.pi * 80 * x) + \
2.8 * np.sin(2 * np.pi * 190 * x) + \
5.1 * np.sin(2 * np.pi * 300 * x)
yy = fft(y) # 快速傅里叶变换
y_real = yy.real # 获取实数部分
y_imag = yy.imag # 获取虚数部分
yf = abs(fft(y)) # 取绝对值
yf1 = 2 * abs(fft(y)) / len(x) # 归一化处理
yf2 = yf1[range(int(len(x) / 2))] # 由于对称性,只取一半区间
xf = np.arange(len(y)) # 频率
xf1 = xf
xf2 = xf[range(int(len(x) / 2))] # 取一半区间
plt.figure(figsize=(10, 4))
plt.subplot(231)
plt.plot(x[0:50], y[0:50])
plt.subplot(232)
plt.plot(xf, y_real, 'r')
plt.subplot(233)
plt.plot(xf, y_imag, 'g')
plt.subplot(234)
plt.plot(xf1, yf, 'g')
plt.subplot(235)
plt.plot(xf1, yf1, 'r')
plt.subplot(236)
plt.plot(xf2, yf2, 'b')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment