0
$\begingroup$

I'm trying to do autocorrelation with numpy in python but i'm getting strange results :

For a simple 440Hz sine wave sample : enter image description here

This is the result of autocorrelation : enter image description here

Is this normal ? Maybe I'm not understanding everything

UPDATE :

Here is my code :

def autocorrelation(signal):
  res = np.correlate(signal, signal, mode='same')
  res = res[len(res)//2:]
  plt.plot(signal)
  plt.show()
  plt.plot(res)

  plt.show()
$\endgroup$
  • 1
    $\begingroup$ No it's not normal for a pure sine wave. $\endgroup$ – Fat32 May 30 '17 at 19:20
  • $\begingroup$ @Fat32 Do you have any idea / explanation ? I noticed that when I apply a window to the signal the correlation works well... $\endgroup$ – Hugo Pauget May 30 '17 at 19:22
  • $\begingroup$ you don't have to apply a window. I cannot comment on numpy as I have only checked for xcorr of matlab. Whatever function you may use you should not get this noise as the output of an autocorrelator. Also note that signal of length 500 producing autocorrelation of length 250 is not usual either. you are doing something wrong. put your code for better responses. $\endgroup$ – Fat32 May 30 '17 at 19:53
  • $\begingroup$ Ok thank you. I updated my post. The lenght is normal as I'm retrieving the half of the correlation function, but I don't know why I'm getting this weird result $\endgroup$ – Hugo Pauget May 30 '17 at 20:14
  • $\begingroup$ Your code works for me when I call it with signal=np.sin(2*np.pi*440*np.arange(0,4.0/f, 1.0/16000)) i.e. a 440Hz sine wave sampled at 16kHz and a duration of 4 cycles. $\endgroup$ – Atul Ingle May 30 '17 at 20:24
3
$\begingroup$

I think you have some overflow/underflow issues? At about 32768, there are signal glitches in the autocorrelation results. Could it be that your calculations are done on 16 bits?

| improve this answer | |
$\endgroup$
  • $\begingroup$ That was exactly the problem, thank you very much! My code reading the wave file was : data = np.fromstring(wav.readframes(-1), 'Int16') so I updated it to data = np.fromstring(wav.readframes(-1), 'Int16').astype('Int64') and it worked like a charm ! However I'm wondering if it's the best solution... $\endgroup$ – Hugo Pauget May 30 '17 at 20:39
  • $\begingroup$ you can typecast them to float before calling np.correlate. $\endgroup$ – Atul Ingle May 30 '17 at 21:01
  • $\begingroup$ i don't do python or numpy but doesn't it normally work on floating-point numbers? $\endgroup$ – robert bristow-johnson May 31 '17 at 2:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.