1、导入相应的包
import math
import numpy as np
from numpy import cos,sin,pi
from scipy.fftpack import fft,ifft
2、 定义 FFT
def my_fft(arr):
length = len(arr)
M = math.log(length, 2) if length == 2**math.log(
length, 2) else int(math.log(length, 2)) + 1
M = int(M)
for i in range(len(arr), int(2**M)):
arr.append(0)
N = len(arr)
array = [i for i in range(N)]
def reverse(a):
L = M
for i in range(N):
a[i] = (a[i >> 1] >> 1) | ((i & 1) << (L - 1))
def butterfly(xn, x1_point, x2_point, Wn):
T = xn[x2_point] * Wn
result1 = xn[x1_point] + T
result2 = xn[x1_point] - T
xn[x1_point] = result1
xn[x2_point] = result2
def creat_wn(m, j):
m = 2**m
return cos(2 * pi * m * j / N) - sin(2 * pi * m * j / N) * 1j
def single__fft(m, xn):
point_distance = pow(2, m - 1)
group_distance = 2 * point_distance
group_count = length // group_distance
group_header = 0
for i in range(group_count):
group_header = i * group_distance
for j in range(group_distance // 2):
'''
级数 1 2 3 .... M
下标 2^(M) 2^(M-1) 2^(M-2) 2^0
可得第i级 Wx 的下标为 x = N/(2**(M-i))
'''
w = creat_wn(M - m, j)
x1 = j + group_header
x2 = x1 + point_distance
butterfly(xn, x1, x2, w)
reverse(array)
new_array = []
for i in range(length):
new_array.append(arr[array[i]])
for i in range(1, M + 1):
single__fft(i, new_array)
print(new_array)
3、测试
arr = [1,3,2,1]
my_fft(arr)
fft(arr)
4、 测试结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/bada2db883a34c318ccc2cc207975d5d.png#pic_center)