Reputation: 611
Hey all, so I'm implementing the simple version of the discrete fourier transform in python for a class, but something strange is happening to my output and I have no idea why. For example if my input is [a,b,c,d] the values are getting scrambled like [a',d',c',b'] with the head of the list in the same place, but the other values reversed. This is my code:
def DFT(pts, carr):
t = time.clock()
F =[0]*pts
for k in range(pts):
c = 2j*k*math.pi/pts
for n in range(pts):
F[k] += complex(carr[n]) * cmath.exp(n*c)
t = time.clock()-t
print(str(pts) + " point DFT finished in " + str(t) + "s")
return F
It's super simple, but for some reason it's flipping the array around all willy-nilly and I have no idea why. Does someone know what's going on here? I'm certain the input is in the right order.
Upvotes: 1
Views: 193
Reputation: 41516
I believe you're missing a negative sign in the calculation of c
(see this link).
With your code:
>>> DFT(4, [1, 2, 3, 4])
4 point DFT finished in 0.0310370227732s
[(10+0j), (-2.0000000000000004-1.9999999999999996j), (-2+9.797174393178826e-16j), (-1.9999999999999982+2.000000000000001j)]
With the missing negative sign:
>>> DFT(4, [1, 2, 3, 4])
4 point DFT finished in 4.17962941128e-05s
[(10+0j), (-2.0000000000000004+1.9999999999999996j), (-2-9.797174393178826e-16j), (-1.9999999999999982-2.000000000000001j)]
Upvotes: 4
Reputation: 56931
In the particular piece of code you have provided, we don't see any list manipulation except for assignment to F. There again you need not use += operator and justing using = is fine. Apart from that, consider this simple case of list assignment, which may help you to track the problem in your code.
When you assign a list to a new list. They reference to the same object. So, if you modify the new one the original one gets modified too. I am assuming that something long these lines in happening in your code.
>>> l = [1,2,3,4]
>>> n = l
>>> n.reverse()
>>> n
[4, 3, 2, 1]
>>> l
[4, 3, 2, 1]
Upvotes: -1