用fft对信号作频谱分析代码提供
时间: 2023-04-03 14:05:11 浏览: 138
以下是使用 C 语言实现 FFT 的代码示例:
#include <stdio.h>
#include <math.h>
#define PI 3.14159265358979323846
void fft(double *x, double *y, int n)
{
int i, j, k, m;
double xt, yt, c, s, t1, t2;
for (i = 0, j = 0; i < n; i++) {
if (j > i) {
xt = x[j];
x[j] = x[i];
x[i] = xt;
yt = y[j];
y[j] = y[i];
y[i] = yt;
}
m = n / 2;
while (m >= 2 && j >= m) {
j -= m;
m /= 2;
}
j += m;
}
for (k = 1; k < n; k *= 2) {
for (i = 0; i < n; i += 2 * k) {
for (j = i; j < i + k; j++) {
c = cos(-PI * (j - i) / k);
s = sin(-PI * (j - i) / k);
t1 = x[j + k] * c - y[j + k] * s;
t2 = x[j + k] * s + y[j + k] * c;
x[j + k] = x[j] - t1;
y[j + k] = y[j] - t2;
x[j] += t1;
y[j] += t2;
}
}
}
}
int main()
{
int i, n;
double x[1024], y[1024];
printf("请输入信号长度:");
scanf("%d", &n);
printf("请输入信号:\n");
for (i = 0; i < n; i++) {
scanf("%lf", &x[i]);
y[i] = 0;
}
fft(x, y, n);
printf("频率\t幅度\n");
for (i = 0; i < n; i++) {
printf("%d\t%lf\n", i, sqrt(x[i] * x[i] + y[i] * y[i]));
}
return 0;
}
阅读全文