It’s easy to verify using MATLAB. Wrong code, mirroring yours:

>> x=1; Draws=[]; for i=1:100000; xs=x+randn(1); y=(xs*exp(-xs))/(x*exp(-x)); if y>rand(1); x=xs; Draws=[Draws; x]; end; end;

>> histogram(Draws, ‘Normalization’, ‘pdf’); hold on; XGamma=[0:.01:10]; YGamma=XGamma.*exp(-XGamma); plot(XGamma, YGamma); hold off;

Correct code, with only the “end” changing places by a bit:

>> x=1; Draws=[]; for i=1:100000; xs=x+randn(1); y=(xs*exp(-xs))/(x*exp(-x)); if y>rand(1); x=xs; end; Draws=[Draws; x]; end;

>> histogram(Draws, ‘Normalization’, ‘pdf’); hold on; XGamma=[0:.01:10]; YGamma=XGamma.*exp(-XGamma); plot(XGamma, YGamma); hold off;

I don’t think the key issue, really, is throwing away the proposals BEFORE calculating the acceptance ratio. It’s simply moving on and not “staying at” the previous value.

If I’m wrong about this, I’d appreciate learning why.

]]>