Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get two frequency spikes from a simple sin function via FFT in R?

I learned about fourier transformation in mathematics classes and thought I had understood them. Now, I am trying to play around with R (statistical language) and interpret the results of a discrete FFT in practice. This is what I have done:

x = seq(0,1,by=0.1)
y = sin(2*pi*(x))

calcenergy <- function(x) Im(x) * Im(x) + Re(x) * Re(x)

fy <- fft(y)
plot(x, calcenergy(fy))

and get this plot:

energy density spectrum of sin(2*pi*(x)) from 0 to 1 with a 0.1 step

If I understand this right, this represents the 'half' of the energy density spectrum. As the transformation is symmetric, I could just mirror all values to the negative values of x to get the full spectrum.

However, what I dont understand is, why I am getting two spikes? There is only a single sinus frequency in here. Is this an aliasing effect?

Also, I have no clue how to get the frequencies out of this plot. Lets assume the units of the sinus function were seconds, is the peak at 1.0 in the density spectrum 1Hz then?

Again: I understand the theory behind FFT; the practical application is the problem :).

Thanks for any help!

like image 332
Peter Müller Avatar asked May 11 '12 09:05

Peter Müller


2 Answers

For a purely real input signal of N points you get a complex output of N points with complex conjugate symmetry about N/2. You can ignore the output points above N/2, since they provide no useful additional information for a real input signal, but if you do plot them you will see the aforementioned symmetry, and for a single sine wave you will see peaks at bins n and N - n. (Note: you can think of the upper N/2 bins as representing negative frequencies.) In summary, for a real input signal of N points, you get N/2 useful complex output bins from the FFT, which represent frequencies from DC (0 Hz) to Nyquist (Fs / 2).

like image 58
Paul R Avatar answered Oct 06 '22 01:10

Paul R


To get frequencies from the result of an FFT you need to know the sample rate of the data that was input to the FFT and the length of the FFT. The center frequency of each bin is the bin index times the sample rate divided by the length of the FFT. Thus you will get frequencies from DC (0 Hz) to Fs/2 at the halfway bin.

The second half of the FFT results are just complex conjugates of the first for real data inputs. The reason is that the imaginary portions of complex conjugates cancel, which is required to represent a summed result with zero imaginary content, e.g. strictly real.

like image 21
hotpaw2 Avatar answered Oct 06 '22 00:10

hotpaw2