简体   繁体   English

python和FFT相频谱

[英]Phase spectrum with python and FFT

I'm trying to calculate a phase spectrum of sinusoid. 我正在尝试计算正弦波的相位谱。 The following code generates 1Hz sinusoid with zero initial phase. 以下代码生成初始相位为零的1Hz正弦波。

import numpy
from numpy import pi, sin, arange
from pylab import plot, show, xlabel, ylabel, xlim, grid

sampling_rate = 500
sampling_time = 1 / sampling_rate
length = 1 # in seconds
n = sampling_rate * length # number of points

time = arange(0, n * sampling_time, sampling_time)
# Generate sinusoid: frequency=1Hz, phase=0
signal = sin(2 * pi * time)

fft = numpy.fft.fft(signal)
fft_phase = numpy.angle(fft)
fft_freq = numpy.arange(n) * sampling_rate / n

plot(fft_freq, fft_phase)
ylabel("FFT Angle")
xlabel("Frequency (Hz)")
xlim(left=0, right=5)
grid(True)
show()

But result doesn't match my expectations. 但是结果不符合我的期望。 It has non-zero phase of 1 Hz component: 它具有1 Hz分量的非零相位:

在此处输入图片说明

It shows incorrect phase of 1 Hz harmonic. 它显示1 Hz谐波的相位不正确。 What's wrong with the code (or approach)? 代码(或方法)有什么问题?

When the magnitude is zero, then the phase is given by numerical imprecision. 当幅度为零时,则相位由数值不精确度给出。

If you display the values computed by fft you'll see that the values you expect to be 0 are actually in the order of 1e-16 or something like that. 如果显示由fft计算的值,则会看到您期望为0的值实际上在1e-16左右。 This is numerical imprecision caused by rounding in the floating-point computations. 这是浮点计算中舍入导致的数值不精确性。

The solution is to compute both the magnitude and the phase, and ignore the phase component if the magnitude is too small. 解决方案是同时计算幅度和相位,如果幅度太小,则忽略相位分量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM