#include #include #include #include #include const double PI = std::acos(-1); const std::complex i(0, 1); using namespace std::complex_literals; // (Slow) DFT std::vector> dft(const std::vector> &v) { std::vector> result(v.size(), 0); const double N = v.size(); for (int k = 0; k < v.size(); k++) { for (int j = 0; j < result.size(); j++) { result[k] += v[j] * std::exp(-i * 2. * PI * double(k * j) / N); } } return result; } // Cooley-Tukey std::vector> fft1(const std::vector> &v) { std::vector> result(v.size(), 0); return result; } std::vector freqs{ 2, 5, 11, 17, 29 }; // known freqs for testing void generate(std::vector>& v) { for (int i = 0; i < v.size(); i++) { v[i] = 0.; // sum several known sinusoids into v[] for(int j = 0; j < freqs.size(); j++) v[i] += sin(2 * M_PI * freqs[j] * i / v.size() ); } } // separate even/odd elements to lower/upper halves of array respectively. // Due to Butterfly combinations, this turns out to be the simplest way // to get the job done without clobbering the wrong elements. void separate (complex* a, int n) { complex* b = new complex[n/2]; // get temp heap storage for(int i=0; i* X, int N) { if(N < 2) { // bottom of recursion. // Do nothing here, because already X[0] = x[0] } else { separate(X,N); // all evens to lower half, all odds to upper half fft2(X, N/2); // recurse even items fft2(X+N/2, N/2); // recurse odd items // combine results of two half recursions for(int k=0; k e = X[k ]; // even complex o = X[k+N/2]; // odd // w is the "twiddle-factor" complex w = exp( complex(0,-2.*M_PI*k/N) ); X[k ] = e + w * o; X[k+N/2] = e - w * o; } } } int main(int argc, char* argv[]) { std::vector> v(1024, 0); generate(v); std::vector> v_dft = dft(v); std::vector> v_fft = fft1(v); if (v_dft != v_fft) { std::cout << "Error: Results differ!\n"; return 1; } return 0; }