使用C语言中的fftw.h计算FFT和IFFT

5

大家好,我正在使用fftw C库来计算嵌入式系统上的一些信号处理应用程序的频谱。但是,在我的项目中,我遇到了一些小问题。

下面是一个简单的程序,我编写它是为了确保我正确实现了fftw函数。基本上,我想计算12个数字序列的fft,然后进行ifft,并再次获得相同的数字序列。如果您已经安装了fftw3和gcc,那么只需使用以下命令编译即可运行此程序:

gcc -g -lfftw3 -lm fftw_test.c -o fftw_test

目前我的fft长度与输入数组大小相同。

#include <stdio.h>
#include <stdlib.h>
#include <sndfile.h>
#include <stdint.h>
#include <math.h>
#include <fftw3.h>

int main(void)
{
double array[] = {0.1, 0.6, 0.1, 0.4, 0.5, 0, 0.8, 0.7, 0.8, 0.6, 0.1,0};
//double array2[] = {1, 6, 1, 4, 5, 0, 8, 7, 8, 6, 1,0};
double *out;
double *err;
int i,size = 12;

fftw_complex *out_cpx;

fftw_plan fft;
fftw_plan ifft;
out_cpx = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*size);
out = (double *) malloc(size*sizeof(double));
err = (double *) malloc(size*sizeof(double));

fft = fftw_plan_dft_r2c_1d(size, array, out_cpx, FFTW_ESTIMATE);  //Setup fftw plan for fft
ifft = fftw_plan_dft_c2r_1d(size, out_cpx, out, FFTW_ESTIMATE);   //Setup fftw plan for ifft

fftw_execute(fft);
fftw_execute(ifft);

//printf("Input:    \tOutput:    \tError:\n");
printf("Input:    \tOutput:\n");
for(i=0;i<size;i++)
{
err[i] = abs(array[i] - out[i]);    
printf("%f\t%f\n",(array[i]),out[i]);
//printf("%f\t%f\t%f\n",(array[i]),out[i],err[i]);
}

fftw_destroy_plan(fft);
fftw_destroy_plan(ifft);
fftw_free(out_cpx);
free(err);
free(out);
return 0;
}

这将产生以下输出:

Input:      Output:
0.100000    1.200000
0.600000    7.200000
0.100000    1.200000
0.400000    4.800000
0.500000    6.000000
0.000000    0.000000
0.800000    9.600000
0.700000    8.400000
0.800000    9.600000
0.600000    7.200000
0.100000    1.200000
0.000000    0.000000

显然ifft产生了一些放大的结果。在这里找到的fftw文档: 关于缩放的fftw文档。 它提到了一些缩放,但我正在使用“r2c”和“c2r”变换,而不是FFT_FORWARD和FFT_BACKWARD。任何见解都将不胜感激。

3个回答

5

查看您使用的函数的文档,您将看到您正在使用FFT_FORWARD和FFT_BACKWARD,并确切地知道它们的用途。因此,您之前发现的缩放信息也适用于这里。


1
好的,谢谢。其实我之前确实读过这个。今天真是太累了... 是的,问题已经解决了:out[i] = out[i]/size; - digiphd

2

非常感谢,我很感激你的意见 :) 我现在正在阅读文档。 - digiphd

1
r2c和c2r基本上与常规傅里叶变换相同,唯一的区别在于输入和输出数组都需要保存一半的数字。请查看 FFTW r2c和c2r手册的最后一段。因此,规范化因子正好是实数数组的元素数量,或者在您的情况下等于变量size(== 12)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接