python实现傅里叶变换和反变换

首先理解下傅里叶变换
如果还看不懂傅里叶变换,请掐死我吧!

import numpy as np
from math import *
x=[1,2,3,4,5]

'''傅里叶变换'''
def fft(x):
    x = np.asarray(x, dtype=float)
    N = x.shape[0]
    n = np.arange(N)
    k = n.reshape((N, 1))
    M = np.exp(-2j * np.pi * k * n / N)
    f = np.dot(M, x)
    return f

##########C++里没有numpy包,需要循环遍历####################
def fft1(a):
    N = len(a)
    f = []
    for k in range(N):
        F = 0
        for m in range(N):
            F += a[m] * e**(-2j * pi * (m*k) / N)
        f.append(F)
    return f

############三角函数代替指数函数#################
def fft2(data):
    length=len(data)
    fftdata = [0+0j]*length
    print(fftdata)
    for k in range(length):
        for i in range(length):
            fftdata[k] += data[i]*(cos(-2*pi*k*i/length)+1j*sin(-2*pi*k*i/length))
    return fftdata

'''傅里叶反变换'''
def ifft1(a):
    N = len(a)
    f = []
    for k in range(N):
        F = 0
        for m in range(N):
            F += a[m] * e**(2j * pi * (m*k) / N)/N
        f.append(F)
    return f

############三角函数代替指数函数#################
def ifft2(data):
    length=len(data)
    ifftdata = [0+0j]*length
    print(ifftdata)
    for k in range(length):
        for i in range(length):
            ifftdata[k] += data[i]*(cos(2*pi*k*i/length)+1j*sin(2*pi*k*i/length))/length
    return ifftdata

你可能感兴趣的:(python)