forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fft.py
51 lines (41 loc) · 1.06 KB
/
fft.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from random import random
from cmath import exp, pi
from math import log2
def cooley_tukey(X):
N = len(X)
if N <= 1:
return X
even = cooley_tukey(X[0::2])
odd = cooley_tukey(X[1::2])
temp = [i for i in range(N)]
for k in range(N//2):
temp[k] = even[k] + exp(-2j*pi*k/N) * odd[k]
temp[k+N//2] = even[k] - exp(-2j*pi*k/N)*odd[k]
return temp
def bitReverse(X):
N = len(X)
temp = [i for i in range(N)]
for k in range(N):
b = sum(1<<(int(log2(N))-1-i) for i in range(int(log2(N))) if k>>i&1)
temp[k] = X[b]
temp[b] = X[k]
return temp
def iterative_cooley_tukey(X):
N = len(X)
X = bitReverse(X)
for i in range(1, int(log2(N)) + 1):
stride = 2**i
w = exp(-2j*pi/stride)
for j in range(0, N, stride):
v = 1
for k in range(stride//2):
X[k + j + stride//2] = X[k + j] - v*X[k + j + stride//2];
X[k + j] -= (X[k + j + stride//2] - X[k + j]);
v *= w;
return X
X = []
for i in range(64):
X.append(random())
Y = cooley_tukey(X)
Z = iterative_cooley_tukey(X)
print(all(abs([Y[i] - Z[i] for i in range(64)][j]) < 1 for j in range(64)))