vendredi 13 mars 2015

Cross Correlation of random variables in python

I have a question which is troubling me for sometime. Say I pick two consecutive random numbers x1 and x2, and then compute its cross correlation, i.e. - , this quantity should go to zero, if I average over large sample size. Also the correlation of - should also go to zero for x1 not equal to x2.


Here is a python code to do the same, but the problem is, I find it does not go to zero, but saturates to small non zero value. I take numbers from Gaussian random numbers



from __future__ import division
import numpy as np
import matplotlib.pyplot as plt


N = 2
std = 0.5
NMC_arr = [10000,100000,1000000]
Cx_arr = np.zeros(len(NMC_arr))
Cx2_arr = np.zeros(len(NMC_arr))
n = 1

#eqb values
xeqb = 0
x2eqb = std**2

for idx,NMC in enumerate(NMC_arr):


#create an array of N X NMC random numbers
random_arr = np.random.normal(0,std,N*NMC)
# then reshape it
random_arr = np.reshape(random_arr,(NMC,N))

#find correlation between 0 and nth element
Cx = 0
Cx2 = 0

for i in xrange(NMC):

x = random_arr[i]
Cx += x[0]*x[n]
Cx2 += x[0]**2 *x[n]**2


Cx/=(NMC)
Cx2/=(NMC)

Cx -= xeqb*xeqb
Cx2 -= x2eqb*x2eqb

Cx_arr[idx]=Cx
Cx2_arr[idx]=Cx2




print Cx_arr,Cx2_arr
plt.plot(NMC_arr,Cx_arr,label='X corr')
plt.plot(NMC_arr,Cx2_arr,label = 'X2 corr')
plt.xscale('log')
plt.legend()
plt.show()


!(http://ift.tt/1MxqUod)





Aucun commentaire:

Enregistrer un commentaire