Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. (* simple probability distribution *)
  2. rho[x_]:=If[x<0||x>1,0,1];
  3. (* empty array storing the markov chain *)
  4. xlist=ConstantArray[0,ntrials];
  5. (* start x at 0.5, do 10^6 trials, and *)
  6. xcur=0.5;
  7. ntrials=10^6;
  8. delta=0.05;
  9. propose:=RandomReal[{-delta,delta}];
  10.  
  11. (* populate the Markov chain *)
  12. Do[
  13. xprop=xcur+propose;
  14. If[RandomReal[]<rho[xprop]/rho[xcur],xcur=xprop];
  15. xlist[[i]]=xcur; (* Could also write AppendTo[xlist,xprop] but it would be slower. *)
  16. ,{i,1,ntrials}];
  17.  
  18. ListLinePlot[xlist[[1;;1000]],PlotLabel->"Part of the markov chain",PlotRange->{-0.01,1.01}]
  19.  
  20. (* binning error calculation. Note the extra factor of M \[Equal] Length[bins] *)
  21. binnedError[binsize_]:=
  22. Module[{bins,abar},
  23. bins=Mean/@Partition[xlist,binsize];
  24. abar=Mean[bins];
  25. Sqrt[Total[(bins-abar)^2]/Length[bins]^2]
  26. ];
  27.  
  28. (* Plot the error estimates over increasing bin size. *)
  29. errorlist=Table[{i,binnedError[i]},{i,1,10000,10}];
  30. maxerror=Max[errorlist[[All,2]]];
  31. Show[
  32. ListLinePlot[errorlist,PlotRange->All,AxesLabel->{"bin size","error"},
  33. PlotLabel->"Binned Error Estimates of Mean[xlist]="<>ToString[Mean[xlist]]],
  34. Plot[maxerror,{i,1,10000},PlotStyle->{Thick,Dashed,Red}]
  35. ]
  36.  
  37. (* Plot the autocorrelation and estimate the autocorrelation time *)
  38. autocorrelation[i_]:=Mean[xlist[[1;;-i]]xlist[[i;;]]]-Mean[xlist[[1;;-i]]]Mean[xlist[[i;;]]];
  39. autos=Table[{i,autocorrelation[i]},{i,1,2000,10}];
  40. (* fit it to an exponentially decreasing curve. We discard c but we need it for the fit *)
  41. fit=FindFit[autos,c E^(-x/tau),{c,tau},x];
  42. (* Plot everything with fancy formatting. *)
  43. Show[
  44. Plot[c E^(-n/tau)/.fit,{n,0,2000},PlotRange->All,PlotLegends->{"fit"},
  45. PlotStyle->Directive[Dashed,Thin,Red],AxesLabel->{"n","correlator"}],
  46. ListPlot[autos,PlotRange->All,PlotLegends->{"data"}],
  47. PlotLabel->"Autocorrelation time estimated to be "<>ToString[tau/.fit]
  48. ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement