我正在尝试采用FFT并绘制它。问题是,我的代码适用于小频率(如50),但不适用于我需要的更大频率。我的代码怎么了?!我希望在输入的正弦波频率上看到尖峰,但是尖峰的频率取决于我使用的样本间距。
bins = 600
ss = 2048
freq = 44100
centerfreq = freq*bins/ss
# Number of samplepoints
N = ss
# sample spacing
T = 1 / 800.
x = np.linspace(0.0, N*T, N)
y = sin(2*np.pi*centerfreq*x)
yf = fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]), 'r')
答案 0 :(得分:2)
代码是对的,你需要刷新傅里叶理论和奈奎斯特采样定理,并确保数字有意义。问题在于你的x轴刻度。绘图功能将x中的第一项与y中的第一项进行绘图,如果x未按比例缩放到您的预期,则表示您感到意外。如果您绘制正弦信号(正弦波)并期望“度”,您也会看到这种情况。你会得到弧度。你有责任扩大规模,以符合你的期望。
请参阅此SO答案https://stackoverflow.com/a/25735436/2061422。
from scipy import *
from numpy import *
from pylab import * # imports for me to get going
bins = 600
ss = 2048
freq = 44100
centerfreq = freq*bins/ss
print centerfreq
# Number of samplepoints
N = ss
# sample spacing
T = 1. / freq # i have decreased the spacing considerably
x = np.linspace(0.0, N*T, N)
sample_spacing = x[1] - x[0] # but this is the real sample spacing
y = sin(2*np.pi*centerfreq*x)
yf = fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
freqs = np.fft.fftfreq(len(y), sample_spacing) # read the manual on this fella.
plt.plot(freqs[:N/2], 1.0/N * np.abs(yf[0:N/2]), 'r')
plt.grid()
plt.show()