cross correlation using fft producing inaccurate results

481 views Asked by At

I tried posting this question last week, but since it wasn't answered I decided to rewrite the question with a simpler, more direct format.

I am using r to compute the cross correlation between two timeseries. As an example, I am taking the two timeseries, which are just sin waves lagged slightly:

x = rnorm(100)
y = rnorm(100)
#x = (x - mean(x))/sd(x) 
#y = (y-mean(y))/sd(y)
zeroPad = rep(0,200)
x0 = zeroPad    
y0 = zeroPad
x0[1:100] = x
y0[1:100] = y


ccf = ccf(x,y,lag.max = 100,plot=F)
ccf = ccf$acf
ccf2 = 2*Re(fft((1/length(x0))*fft(x0)*(1/length(x0))*fft(rev(y0)),inverse  =T))
ccf2 = c(ccf2[(length(ccf2)-length(x)+1):length(ccf2)],ccf2[1:length(x)])

plot(ccf,type="l")
lines(ccf2,col=2)

According to this post: https://dsp.stackexchange.com/questions/736/how-do-i-implement-cross-correlation-to-prove-two-audio-files-are-similar and sevreral others, the outputs ccf1 and ccf2 should be the same: one of them is computed the normal way in the time domain, and the other is computed as a convolution in the frequency domain. However, The output I am getting looks like this:

enter image description here

Does anyone know why there is this error/discrepancy? In certain cases it is much worse -- this was just an easily reproducible example.

0

There are 0 answers