手动FFT不能给我与FFT相同的结果 [英] Manual fft not giving me same results as fft
问题描述
import numpy as np
import matplotlib.pyplot as pp
curve = np.genfromtxt('C:\Users\latel\Desktop\kool\Neuro\prax2\data\curve.csv',dtype = 'float', delimiter = ',')
curve_abs2 = np.empty_like(curve)
z = 1j
N = len(curve)
for i in range(0,N-1):
curve_abs2[i] =0
for k in range(0,N-1):
curve_abs2[i] += (curve[i]*np.exp((-1)*z*(np.pi)*i*((k-1)/N)))
for i in range(0,N):
curve_abs2[i] = abs(curve_abs2[i])/(2*len(curve_abs2))
#curve_abs = (np.abs(np.fft.fft(curve)))
#pp.plot(curve_abs)
pp.plot(curve_abs2)
pp.show()
#后面的代码为我提供了3个值.但这只是...不同
The code behind # gives me 3 values. But this is just ... different
错误的^^这段代码: http://www.upload.ee/image/3922681/Ex5problem.png
Wrong ^^ this code: http://www.upload.ee/image/3922681/Ex5problem.png
使用numpy.fft.fft()进行更正: http://www.upload. ee/image/3922682/Ex5numpyformulas.png
Correct using numpy.fft.fft(): http://www.upload.ee/image/3922682/Ex5numpyformulas.png
推荐答案
有几个问题:
-
您正在为
curve_abs2
的元素分配复杂的值,因此应声明为复杂的,例如curve_abs2 = np.empty_like(curve, dtype=np.complex128)
. (我建议使用名称curve_fft
代替curve_abs2
.)
You are assigning complex values to the elements of
curve_abs2
, so it should be declared to be complex, e.g.curve_abs2 = np.empty_like(curve, dtype=np.complex128)
. (And I would recommend using the name, say,curve_fft
instead ofcurve_abs2
.)
在python中,range(low, high)
给出了序列[low, low + 1, ..., high - 2, high - 1]
,因此必须使用range(0, N)
(如果需要,可以将其简化为range(N)
),而不是range(0, N - 1)
.
In python, range(low, high)
gives the sequence [low, low + 1, ..., high - 2, high - 1]
, so instead of range(0, N - 1)
, you must use range(0, N)
(which can be simplified to range(N)
, if you want).
您的公式中缺少2的因数.您可以使用z = 2j
来解决此问题.
You are missing a factor of 2 in your formula. You could fix this by using z = 2j
.
在内部循环中求和的表达式中,您将curve
索引为curve[i]
,但这应该是curve[k]
.
In the expression that is being summed in the inner loop, you are indexing curve
as curve[i]
, but this should be curve[k]
.
在该表达式中,您无需从k中减去1,因为k
循环的范围是0到N-1.
Also in that expression, you don't need to subtract 1 from k, because the k
loop ranges from 0 to N - 1.
因为k
和N
是整数,并且您正在使用Python 2.7,所以表达式(k-1)/N
中的除法将是整数除法,并且所有k
都将得到0.要解决此问题和上一个问题,可以将该术语更改为k / float(N)
.
Because k
and N
are integers and you are using Python 2.7, the division in the expression (k-1)/N
will be integer division, and you'll get 0 for all k
. To fix this and the previous problem, you can change that term to k / float(N)
.
如果您解决了这些问题,则在第一个双循环结束时,数组curve_abs2
(现在为复杂数组)应与np.fft.fft(curve)
的结果匹配.不会完全一样,但是差异应该很小.
If you fix those issues, when the first double loop finishes, the array curve_abs2
(now a complex array) should match the result of np.fft.fft(curve)
. It won't be exactly the same, but the differences should be very small.
您可以使用numpy向量化计算完全消除该双重循环,但这是另一个问题.
You could eliminate that double loop altogether using numpy vectorized calculations, but that is a topic for another question.
这篇关于手动FFT不能给我与FFT相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!