clc;clear all;close all;
% 从柯西分布采样
% f(x) = 1/(pi*(1+x.^2)
T = 5000;
sigma = 1;thetamin = -30;thetamax = 30;
theta = zeros(T,1);
theta(1) = rand(1)*thetamax*2 - thetamax;
t = 1;
while t<T
t = t+1;
theta_star = normrnd(theta(t-1),sigma);
alpha = min(1,(cauchy(theta_star)/cauchy(theta(t-1))));
u = rand(1);
if u <= alpha
theta(t) = theta_star;
else
theta(t) = theta(t-1);
end
end
subplot(211),plot(1:T,theta,'g-');
num_bins = 50;
subplot(212),hist(theta,num_bins);
hi = findobj(gca,'Type','patch');
hi.FaceColor = 'r';
hi.EdgeColor = 'w';