简体   繁体   中英

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.

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:

在此处输入图片说明

It shows incorrect phase of 1 Hz harmonic. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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