您的位置:首页 > 其它

(模板)FFT

2015-09-22 13:13 155 查看
const double Pi = acos(-1.0);

struct complex {
    double r, i;
    complex(double r = 0, double i = 0):r(r), i(i) {}
    complex operator + (const complex &ot) const {
        return complex(r + ot.r, i + ot.i);
    }
    complex operator - (const complex &ot) const {
        return complex(r - ot.r, i - ot.i);
    }
    complex operator * (const complex &ot) const {
        return complex(r * ot.r - i * ot.i, r * ot.i + i * ot.r);
    }
}x1
, x2
;

void change(complex *y, int len) {
    for(int i = 1, j = len / 2; i < len - 1; ++i) {
        if(i < j) swap(y[i], y[j]);
        int k = len / 2;
        while(j >= k) {
            j -= k;
            k >>= 1;
        }
        j += k;
    }
}

void FFT(complex *y, int len, int on) {
    change(y, len);
    for(int h = 2; h <= len; h <<= 1) {
        complex wn = complex(cos(on * 2 * Pi / h), sin(on * 2 * Pi / h));
        for(int j = 0; j < len; j += h) {
            complex w = complex(1, 0);
            for(int k = j; k < j + h / 2; ++k) {
                complex u = y[k];
                complex t = y[k+h/2] * w;
                y[k] = u + t;
                y[k+h/2] = u - t;
                w = w * wn;
            }
        }
    }
    if(on == -1) {
        for(int i = 0; i < len; ++i)
            y[i].r /= len;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: