Search code examples
randomwolfram-mathematicastochastic-process

The plots of co-variance functions should start from 0-shift


The following was my question given by my teacher,

  1. Generate a sequence of N = 1000 independent observations of random variable with distribution: (c) Exponential with parameter λ = 1 , by inversion method.
  2. Present graphically obtained sequences(except for those generated in point e) i.e. e.g. (a) i. plot in the coordinates (no. obs., value of the obs) ii. plot in the coordinates (obs no n, obs. no n + i) for i = 1, 2, 3. iii. plot so called covariance function for some values. i.e. and averages:

enter image description here

I have written the following code,

(*****************************************************************)
(*Task 01(c) and 02(a)*)
(*****************************************************************)
n = 1000;

taskC = Table[-Log[RandomReal[]], {n}];

ListPlot[taskC, AxesLabel->{"No. obs", "value of the obs"}]

i = 1;
ListPlot[Table[
    {taskC[[k]], taskC[[k+i]]}, 
    {k, 1, n-i,1}],
AxesLabel->{"obs.no.n", "obs.no.n+1"}]

i++;
ListPlot[Table[
    {taskC[[k]], taskC[[k+i]]},
    {k, 1, n-i,1}],
AxesLabel-> {"obs.no.n", "obs.no.n+2"}]

i++;
ListPlot[Table[
    {taskC[[k]], taskC[[k+i]]},
    {k,1,n-i,1}],
AxesLabel->{"obs.no.n", "obs.no.n+3"}]

avg = (1/n)*Sum[taskC[[i]], {i,n}];

ListPlot[Table[1/(n-tau) * Sum[(taskC[[i]]-avg)*(taskC[[i+tau]] - avg), n], {tau, 1,100}], 
    Joined->True, 
    AxesLabel->"Covariance Function"]

enter image description here

He has commented,

The plots of co-variance functions should start from 0-shift. Note that for larger than 0 shifts you are estimating co-variance between independent observations which is zero, while for 0 shift you are estimating variance of observation which is large. Thus the contrast between these two cases is a clear indication that the observations are uncorrelated.

What did I do wrong?

How can I correct my code?


Solution

  • Zero-shift means calculating the covariance for tau = 0, which is simply the variance.

    Labeled[ListPlot[Table[{tau,
        1/(n - tau)*Sum[(taskC[[i]] - avg)*(taskC[[i + tau]] - avg), {i, n - tau}]},
       {tau, 0, 5}], Filling -> Axis, FillingStyle -> Thick, PlotRange -> All,
      Frame -> True, PlotRangePadding -> 0.2, AspectRatio -> 1],
     {"Covariance Function K(n)", "n"}, {{Top, Left}, Bottom}]
    

    enter image description here

    Variance[taskC]
    

    0.93484

    Covariance[taskC, taskC]
    

    0.93484

    (* n = 1 *)
    Covariance[Most[taskC], Rest[taskC]]
    

    0.00926913