Python-FFT:频移

2024-05-12 19:59:45 发布

您现在位置:Python中文网/ 问答频道 /正文

在对信号进行频谱分析时,我遇到了一个奇怪的问题,即绘制的信号频率偏移(或加倍)。这里有一个简单的例子显示了我的方法:用100kHz对1kHz正弦信号进行采样。最后,信号箱显示为2kHz,而不是1kHz

import numpy as np
import matplotlib.pyplot as plt

time_step = 1.0/100e3
t = np.arange(0, 2**14) * time_step

sig = np.sin(2*np.pi*1e3*t)

sig_fft = np.fft.rfft(sig)

#calculate the power spectral density
sig_psd = np.abs(sig_fft) ** 2 + 1

#create the frequencies
fftfreq = np.fft.fftfreq(len(sig_psd), d=time_step)

#filter out the positive freq
i = fftfreq > 0

plt.plot(fftfreq[i], 10*np.log10(sig_psd[i]))
plt.xscale("log")

Tags: theimportffttime信号asstepnp
1条回答
网友
1楼 · 发布于 2024-05-12 19:59:45

您使用了错误的函数来计算频率。实信号的FFT变换具有负频率分量,负频率分量是正频率分量的复共轭,即频谱是厄米对称的rfft()利用这一事实,不输出负频率,只输出直流分量和正频率。因此,sig_psd的长度是使用fft()而不是rfft()并将其传递给fftfreq()时所得到的长度的两倍,有效地使频率加倍

解决方案:改用rfftfreq()

import numpy as np
import matplotlib.pyplot as plt

time_step = 1.0/100e3
t = np.arange(0, 2**14) * time_step

sig = np.sin(2*np.pi*1e3*t)

sig_fft = np.fft.rfft(sig)

#calculate the power spectral density
sig_psd = np.abs(sig_fft) ** 2 + 1

#create the frequencies
fftfreq = np.fft.rfftfreq(len(sig), d=time_step)  # <  note: len(sig), not len(sig_psd)

#filter out the positive freq
i = fftfreq > 0  # <  note: Not really needed, this just removes the DC component

plt.plot(fftfreq[i], 10*np.log10(sig_psd[i]))
plt.xscale("log")

相关问题 更多 >