A random sample of length n drawn from Bernoulli distribution with probability of success prob, that has a correlation c with itself shifted back lag steps, can be generated using following procedure,

SampleWithCorr:=proc(prob::And(numeric,satisfies(c->c>=0 and c<=1)),
lag::posint,c::And(numeric,satisfies(c->c<=1 and c>=-1)),n::posint)
local X,B,S,C,s,i;
uses Statistics;
X:=RandomVariable(Bernoulli(prob));
S:=Sample(X,n);
if n<=lag or s=0 then S else
s:=signum(c);
B:=RandomVariable(Bernoulli(abs(c)));
C:=Sample(B,n-lag);
if s=1 then 
for i from lag+1 to n do
if C[i-lag]=1 then S[i]:=S[i-lag] fi od;
else for i from lag+1 to n do
if C[i-lag]=1 then S[i]:=1-S[i-lag] fi od
fi fi; S end:

For example,

S:=SampleWithCorr(1/2,1,-0.7,10000);

                       [ 10000 Element Row Vector ]
                  S := [ Data Type: float[8]      ]
                       [ Storage: rectangular     ]
                       [ Order: Fortran_order     ]

Statistics:-Correlation(S[1..9999],S[2..10000]);

                            -.6973705688

Edit 1: Erik Postma noticed that it gives a distribution with different probability of success in cases with prob not equal 1/2 for negative correlation. Any suggestions?

Acknowledgements: The idea (for prob = 1/2) belongs to alex_01. The implementation (not perfect, but working) is mine. I am thankful to Erik Postma noticing the problem for negative correlations in cases with prob not equal 1/2.

Alec


Please Wait...