写一个FFT算法的C语言实现,输入数组是x,输出数组为y,点数为N
时间: 2023-05-26 14:03:21 浏览: 102
以下为C语言实现FFT算法的代码,代码中实现了输入实数数组x,输出实数数组y,点数为N。
```
#include <stdio.h>
#include <math.h>
// 定义复数结构体
typedef struct {
double re;
double im;
} Complex;
// 定义π常量
const double PI = acos(-1.0);
// 计算FFT算法中旋转因子
void calc_w(int k, int n, Complex *w) {
for (int i = 0; i < n; i++) {
double angle = 2 * PI * k * i / n;
w[i].re = cos(angle);
w[i].im = sin(angle);
}
}
// 执行递归FFT算法
void fft_recursive(Complex *x, Complex *y, int n, int step) {
if (n == 1) {
y[0] = x[0];
return;
}
Complex *x0 = new Complex[n / 2];
Complex *x1 = new Complex[n / 2];
Complex *y0 = new Complex[n / 2];
Complex *y1 = new Complex[n / 2];
Complex w[n];
calc_w(step, n, w);
for (int i = 0; i < n / 2; i++) {
x0[i] = x[2 * i];
x1[i] = x[2 * i + 1];
}
fft_recursive(x0, y0, n / 2, step * 2);
fft_recursive(x1, y1, n / 2, step * 2);
for (int i = 0; i < n / 2; i++) {
y[i].re = y0[i].re + w[i].re * y1[i].re - w[i].im * y1[i].im;
y[i].im = y0[i].im + w[i].re * y1[i].im + w[i].im * y1[i].re;
y[i + n / 2].re = y0[i].re - w[i].re * y1[i].re + w[i].im * y1[i].im;
y[i + n / 2].im = y0[i].im - w[i].re * y1[i].im - w[i].im * y1[i].re;
}
delete[] x0;
delete[] x1;
delete[] y0;
delete[] y1;
}
// 执行FFT算法
void fft(double *x, double *y, int n) {
Complex *cx = new Complex[n];
Complex *cy = new Complex[n];
for (int i = 0; i < n; i++) {
cx[i].re = x[i];
cx[i].im = 0;
}
fft_recursive(cx, cy, n, 1);
for (int i = 0; i < n; i++) {
y[i] = cy[i].re;
}
delete[] cx;
delete[] cy;
}
// 测试程序
int main() {
// 输入数据
int N = 8;
double x[8] = {1, 2, 3, 4, 4, 3, 2, 1};
double y[N];
// 执行FFT算法
fft(x, y, N);
// 输出结果
for (int i = 0; i < N; i++) {
printf("%.2lf + %.2lfi\n", y[i], 0.0);
}
return 0;
}
```
阅读全文