需要注意的是,m需要是长度的2^length,dir==1时为iFFT,dir==-1时为FFT,complex<double> x[]为系数。
/************************************************************************* > File Name: fft.cpp > Author: zhengnanlee > Mail: zhengnanlee@hotmail.com > Created Time: 2013年09月27日 星期五 19时10分50秒 ************************************************************************/ #include <iostream> #include <complex> #include <math.h> using namespace std; void fft(int dir, long m, complex <double> x []) { long i, i1, i2, j, k, l, l1, l2, n; complex<double> tx, t1, u, c; n = 1; for (i = 0; i < m; i++) n <<= 1; i2 = n >> 1; j = 0; for (i = 0; i < n - 1; i++) { if (i < j) swap(x[i], x[j]); k = i2; while (k <= j) { j -= k; k >>= 1; } j += k; } c.real(-1.0); c.imag(0.0); l2 = 1; for (l = 0; l < m; l++) { l1 = l2; l2 <<= 1; u.real(1.0); u.imag(0.0); for (j = 0; j < l1; j++) { for (i = j; i < n; i += l2) { i1 = i + l1; t1 = u * x[i1]; x[i1] = x[i] - t1; x[i] += t1; } u = u * c; } c.imag(sqrt((1.0 - c.real()) / 2.0)); if (dir == 1) c.imag(-c.imag()); c.real(sqrt(1.0 + c.real()) / 2.0); } if (dir == 1) for (i = 0; i < n; i++) x[i] /= n; return; } int main() { complex<double> x[4]; long m = 2; x[0].real(0.0), x[0].imag(5.0), x[1].real(1.0), x[1].imag(1.0), x[2].real(5.0), x[2].imag(7.62), x[3].real(1.0), x[3].imag(6.40); cout << "Before FFT" << endl; for (int i = 0; i < 4; i++) { cout << x[i].real() << ' ' << x[i].imag() << 'i' << endl; } fft(-1, m, x); cout << "After FFT" << endl; for (int i = 0; i < 4; i++) { cout << x[i].real() << ' ' << x[i].imag() << 'i' << endl; } system("pause"); } |