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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#include <complex>
#include "fft.h"
using namespace std;
typedef complex<double> cmplx;
//======================================================================
void FFT( cmplx* f, cmplx* ftilde, int N, int step ) // fast fourier transform
{
if ( N % 2 == 0 ) // recursion if a multiple of 2
{
int N2 = N / 2;
cmplx* g = new cmplx[N2];
cmplx* h = new cmplx[N2];
int step2 = step + step;
FFT( f , g, N2, step2 );
FFT( f + step, h, N2, step2 );
cmplx w = polar( 1.0, -2.0 * pi / N );
cmplx wn = 1.0;
for ( int n = 0; n < N2; n++ )
{
ftilde[n] = g[n] + wn * h[n];
ftilde[n+N2] = g[n] - wn * h[n];
wn *= w;
}
delete [] g;
delete [] h;
}
else // otherwise just do a DFT
{
DFT( f, ftilde, N, step );
}
}
//======================================================================
void DFT( cmplx* f, cmplx* ftilde, int N, int step ) // basic discrete Fourier transform
{
for ( int n = 0; n < N; n++ )
{
ftilde[n] = 0.0;
cmplx w = polar( 1.0, -2.0 * pi * n / N );
cmplx wm = 1.0;
for ( int m = 0, mpos = 0; m < N; m++, mpos += step )
{
ftilde[n] += f[mpos] * wm;
wm *= w;
}
}
}
//======================================================================
void iFFT( cmplx* ftilde, cmplx* f, int N ) // inverse fast fourier transform
{
cmplx* ftildeConjugate = new cmplx[N];
for ( int m = 0; m < N; m++ ) ftildeConjugate[m] = conj( ftilde[m] );
FFT( ftildeConjugate, f, N );
double factor = 1.0 / N;
for ( int m = 0; m < N; m++ ) f[m] = factor * conj( f[m] );
delete [] ftildeConjugate;
}
|