Do Fourier Transformation using Python

时间:2018-12-19 11:13:27

标签: python numpy fft

I'm trying to do Fourier transformation using Python.

There is nice library numpy that have the function fft that supposed according the doc to get series of dots and return the Fourier transformation of them.

Now I try to make it work - but it's looking wrong...

I created simple sine wave 1Hz , Amplitude=1. I sample it with 8Hz (so 8 samples)

These are the samples:

[0,0.707,1,0.707,0,-0.707,-1,-0.707]

Now I expect to get in return the ens. [0,4,0,0,0,0,0,4] or [0,8,0,0] that represents that the frequency is 1Hz (depends if it's does the trimming needed according to Nyquist limit).

But in reality I get the following:

[0.00000000e+00+0.00000000e+00j, -2.22044605e-16-3.99969798e+00j,
 0.00000000e+00+0.00000000e+00j, -2.22044605e-16+3.02022804e-04j,
 0.00000000e+00+0.00000000e+00j,  2.22044605e-16-3.02022804e-04j,
 0.00000000e+00+0.00000000e+00j,  2.22044605e-16+3.99969798e+00j]

This is my code:

import numpy
signal = numpy.array([0,0.707,1,0.707,0,-0.707,-1,-0.707], dtype=float)
f =  numpy.fft.fft(signal)
print (f)

Why am I getting this results? What I do wrong?

1 个答案:

答案 0 :(得分:0)

傅立叶变换的输出

nummpy.fft.fft的输出(以及其他所有Fourier变换方法)具有复数值。此输出对有关输入中每个频率分量的幅度和相移的信息进行编码。您在输出中得到的复数是正确的。

如何从fft.fft的输出中获取频谱

从您的示例中,您似乎试图获得的输出实际上是频谱(从技术上讲,energy spectral density)。您可以通过仅取numpy.fft.fft返回的结果的绝对值来计算该值:

import numpy
signal = numpy.array([0,0.707,1,0.707,0,-0.707,-1,-0.707], dtype=float)
f =  numpy.fft.fft(signal)
print(np.abs(f))

输出:

[0.00000000e+00 3.99969798e+00 0.00000000e+00 3.02022804e-04
 0.00000000e+00 3.02022804e-04 0.00000000e+00 3.99969798e+00]

与您期望的一样,在某些数字误差内。

根据沃伦·韦克瑟(Warren Weckesser)的评论,您可以使用2**.5/2的“实际”值代替简写.707来减少数字误差:

signal = numpy.array([0, 2**.5/2, 1, 2**.5/2, 0, -2**.5/2, -1, -2**.5/2])
f =  numpy.fft.fft(signal)
print(np.abs(f))

输出:

[0.00000000e+00 4.00000000e+00 0.00000000e+00 2.22044605e-16
 0.00000000e+00 2.22044605e-16 0.00000000e+00 4.00000000e+00]

复数的绝对值是其大小。按照Fourier transform wiki

  

傅立叶变换在一个点上的大小是多少频率含量