FFT:如何修改该算法以返回系数表示

FFT: How could this algorithm be modified to return to coefficient representation?

本文关键字:算法 返回 表示 何修改 修改 FFT      更新时间:2023-10-16

下面是Cooley-Tukey FFT算法的base-2实现(在Rosetta Code中找到)。运行一次FFT后,数据数组将从系数表示变为点值表示。怎么转换回系数呢?

#include <complex>
#include <iostream>
#include <valarray>
const double PI = 3.141592653589793238460;
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
// Cooley–Tukey FFT (in-place)
void fft(CArray& x)
{
    const size_t N = x.size();
    if (N <= 1) return;
    // divide
    CArray even = x[std::slice(0, N/2, 2)];
    CArray  odd = x[std::slice(1, N/2, 2)];
    // conquer
    fft(even);
    fft(odd);
    // combine
    for (size_t k = 0; k < N/2; ++k)
    {
        Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k];
        x[k    ] = even[k] + t;
        x[k+N/2] = even[k] - t;
    }
}
int main()
{
    const Complex test[] = { 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0 };
    CArray data(test, 8);
    fft(data);
    for (int i = 0; i < 8; ++i)
    {
        std::cout << data[i] << "n";
    }
    return 0;
}

计算FFT逆

改变
-2 * PI * k / N

2 * PI * k / N

在做逆FFT之后,将输出缩放1/N

添加到Rosetta代码

// inverse fft (in-place)
void ifft(CArray& x)
{
    // conjugate the complex numbers
    std::transform(&x[0], &x[x.size()], &x[0], std::conj<double>);
    // forward fft
    fft( x );
    // conjugate the complex numbers again
    std::transform(&x[0], &x[x.size()], &x[0], std::conj<double>);
    // scale the numbers
    x /= x.size();
}