我在使用Metropolis-Hasting方法评估Matlab中的积分时遇到了一些麻烦。积分是从零到无穷大的e ^(x ^ -2)。我写的代码没有产生任何错误,但是, 1)我不确定它是否正在做我想做的事情 2)即使它做了我想要的事情,我也不太确定如何提取'''代码产生的数据的积分值
clc
clear all
%Parameters for Gaussian proposal distribution N(mu, sigma)
sigma = 1;
mu = 0;
f = @(x) exp(x.^-2); %Target distribution
n = 10000;
step = 1;
x = zeros(1, n); %Storage
x(1) = 1; %Starting point, maximum of function f
for jj = 2:n
xtrial = x(jj-1) + step*normrnd(mu,sigma); %Generates candidate
w = f(xtrial)/f(jj-1);
if w >= 1
x(jj) = xtrial;
else
r = rand(1); %Generates uniform for comparison
if r <= w
x(jj) = xtrial;
end
x(jj) = x(jj-1);
end
end
我觉得这个问题可能非常简单,而且我错过了一些关于这种方法的基本知识。任何帮助都会非常感激,因为我的编程技巧非常基础!
答案 0 :(得分:0)
你的函数在x = 0时没有定义,你写的代码函数f的最大值是x = 1,所以我假设积分是从1到inf。积分的值是x的平均值,为此我得到了结果2.7183,代码如下:
clc
clear all
%Parameters for Gaussian proposal distribution N(mu, sigma)
sigma = 3;
mu = 0;
f = @(x) double(x>1).*exp(x.^-2); %Target distribution
n = 10000;
step = 1;
x = zeros(1, n); %Storage
x(1) = 1; %Starting point, maximum of function f
acc = 0; % vector to track the acceptance rate
for jj = 2:n
xtrial = x(jj-1) + step*normrnd(mu,sigma); %Generates candidate
w = f(xtrial)/f(x(jj-1));
if w >= 1
x(jj) = xtrial;
acc = acc +1;
else
r = rand(1); %Generates uniform for comparison
if r <= w
x(jj) = xtrial;
acc = acc +1;
end
x(jj) = x(jj-1);
end
end
plot(x)
(acc/n)*100
mean(f(x))