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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <iostream>
#include <iomanip>
#include <complex>
using namespace std;
const double pi = 3.14159265358979323846;
using Complex = complex<double>;
void print( const char * prompt, Complex A[], int N );
void FFT ( Complex f[] , Complex ftilde[], int N, int step = 1 );
void DFT ( Complex f[] , Complex ftilde[], int N, int step = 1 );
void iFFT( Complex ftilde[], Complex f[] , int N );
//======================================================================
int main()
{
Complex test[] = { 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0 };
int N = sizeof test / sizeof test[0];
Complex * ft = new Complex[N];
print( "Original:", test, N );
// Forward transform
FFT( test, ft, N ); print( "Transform:", ft, N );
// Invert transform
iFFT( ft, test, N ); print( "Invert:", test, N );
delete [] ft;
}
//======================================================================
void print( const char * prompt, Complex A[], int N )
{
cout << prompt << '\n' << fixed;
for ( int i = 0; i < N; i++ ) cout << A[i] << '\n';
}
//======================================================================
void FFT( Complex f[], Complex ftilde[], int N, int step ) // Fast Fourier Transform
{
if ( N > 2 && N % 2 == 0 ) // Recursion if a multiple of 2
{
int N2 = N >> 1;
Complex* g = new Complex[N];
int step2 = step << 1;
FFT( f , g , N2, step2 );
FFT( f + step, g + N2, N2, step2 );
Complex w = polar( 1.0, -2.0 * pi / N );
Complex wn = 1.0;
for ( int n = 0; n < N2; n++ )
{
if ( n > 0 ) wn *= w;
ftilde[n] = g[n] + wn * g[n+N2];
ftilde[n+N2] = g[n] - wn * g[n+N2];
}
delete [] g;
}
else // Otherwise just do a DFT
{
DFT( f, ftilde, N, step );
}
}
//======================================================================
void DFT( Complex f[], Complex ftilde[], int N, int step ) // Basic Discrete Fourier Transform
{
Complex w = polar( 1.0, -2.0 * pi / N );
Complex wn = 1.0;
for ( int n = 0; n < N; n++ )
{
if ( n > 0 ) wn *= w;
Complex wm = 1.0;
ftilde[n] = 0.0;
for ( int m = 0, mpos = 0; m < N; m++, mpos += step )
{
if ( m > 0 ) wm *= wn;
ftilde[n] += f[mpos] * wm;
}
}
}
//======================================================================
void iFFT( Complex ftilde[], Complex f[], int N ) // Inverse Fast Fourier Transform
{
Complex* ftildeConjugate = new Complex[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] = conj( f[m] ) * factor;
delete [] ftildeConjugate;
}
//======================================================================
| |