Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FFTW results differ from FFT in MATLAB

Tags:

c

matlab

fft

fftw

I compare the forward FFT using FFTW and MATLAB fft. The input signal is a Gaussian. Code:

FFTW using C:

float *signal; /*input signal*/
int nt; /*length of the signal*/
fftw_complex *in, *out;
fftw_plan plan1;

in = fftw_malloc(nt*sizeof(fftw_complex)); 
out = fftw_malloc(nt*sizeof(fftw_complex));
for (j=0;j<nt;j++){
        in[j][0]=(double)signal[j];
        in[j][1]=0.0;
}    
plan1 = fftw_plan_dft_1d(nt, in, out, -1, FFTW_ESTIMATE);
fftw_execute(plan1);        
fftw_destroy_plan(plan1);

for (j=0;j<nt;j++){
        real[j]=(float)out[j][0];
        imag[j]=(float)out[j][1];
}

fft function in MATLAB:

fft(signal);

I plot the real and imaginary parts of both results:

fft vs fftw

The real part are almost the same value, while the imaginary part has quite different values. How to fix this problem?

like image 217
clduan Avatar asked Oct 22 '25 09:10

clduan


1 Answers

You should look at the scale factor of the plot on the left side over the plot of 'Imag'. It says 10^-15. This is quite small in relation to the real signal magnitude (at least the larger parts which is >10^1) so the results are quite similiar.

Floating point algorithms in general tend to not deliver the exact same result as long as they are not implemented exactly in the same way. (And even then they can differ by different options for rounding).

This QA might give some insight: Floating point inaccuracy examples

like image 83
Kami Kaze Avatar answered Oct 25 '25 00:10

Kami Kaze