r/Python • • Aug 28 '13

Understanding the FFT Algorithm (with Python examples)

http://jakevdp.github.io/blog/2013/08/28/understanding-the-fft/
135 Upvotes

13 comments sorted by

View all comments

6

u/Antagonist360 Aug 29 '13 edited Aug 29 '13

There was a Reddit ELI5 post asking about the FFT a while ago that I had commented on and supplied python code for (see below). I ended up copying my response into a blog post.

from cmath import exp,pi

def FFT(X):
    n = len(X)
    w = exp(-2*pi*1j/n)
    if n > 1:
        X = FFT(X[::2]) + FFT(X[1::2])
        for k in xrange(n/2):
            xk = X[k]
            X[k] = xk + w**k*X[k+n/2]
            X[k+n/2] = xk - w**k*X[k+n/2]
    return X  

EDIT woops forgot first two lines of code
EDIT didn't know about cmath exp

4

u/Araucaria Aug 29 '13

...never mind.

7

u/Thirsteh Aug 29 '13

I'd like to see the five-year-old that understood that snippet! :)

Nice blog post!

5

u/Antagonist360 Aug 29 '13

Thanks! Didn't Gauss come up with the FFT at age 5?

9

u/TheBB Aug 29 '13 edited Aug 29 '13

Geez, I thought you were joking, but it's true.

Edit: Although it was in 1805, so he was at least 27. Maybe you got it mixed up with the arithmetic sum story?

3

u/Thirsteh Aug 29 '13

Thanks for making me feel completely inadequate, guys.

3

u/Antagonist360 Aug 29 '13

I thought I was joking too.

4

u/minno I <3 duck typing less than I used to, interfaces are nice Aug 29 '13

Why the e = exp(1)? Just use exp to do the exponentiation.

5

u/jakevdp Aug 29 '13

math.exp can't handle complex numbers. You'd need to use cmath.exp instead.

2

u/isarl Aug 29 '13

So why not use from cmath import exp,pi?

1

u/Antagonist360 Aug 29 '13

Sure that would work. Didn't know about cmath

3

u/skytomorrownow Aug 29 '13

Do you know why you're getting downvoted? New to Python, but this seemed like a valid notion. Is there some reason not to use exp()?