本文介绍了给定PDF生成随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须根据确定的概率密度函数(截短的拉普拉斯算子)生成随机值:
I have to generate random values according to a determined probability density function (a truncated laplacian):
Sigma_Phi = 1;
B = 1/(1-exp(-sqrt(2)*pi/Sigma_Phi));
Phi = -60:0.001:60;
for iter=1:length(Phi)
if Phi(iter) < pi && Phi(iter)>=0
P(iter) = ((B*exp(-abs(sqrt(2)*Phi(iter)/Sigma_Phi)))/(sqrt(2)*Sigma_Phi));
elseif Phi(iter) >= -pi && Phi(iter)<=0
P(iter) = ((B*exp(-abs(sqrt(2)*Phi(iter)/Sigma_Phi)))/(sqrt(2)*Sigma_Phi));
else
P(iter)=0;
end
end
然后我必须在该PDF之后生成随机值,但是我不知道该怎么做.
Then I have to generate random values following that PDF, but I don't know how to do it.
推荐答案
这里是使用逆变换采样:
% for reproducibility
rng(333)
Sigma_Phi = 1;
B = 1/(1-exp(-sqrt(2)*pi/Sigma_Phi));
Phi = -10:0.001:10;
P = nan(length(Phi),1);
for iter=1:length(Phi)
if Phi(iter) < pi && Phi(iter)>=0
P(iter) = ((B*exp(-abs(sqrt(2)*Phi(iter)/Sigma_Phi)))/(sqrt(2)*Sigma_Phi));
elseif Phi(iter) >= -pi && Phi(iter)<=0
P(iter) = ((B*exp(-abs(sqrt(2)*Phi(iter)/Sigma_Phi)))/(sqrt(2)*Sigma_Phi));
else
P(iter)=0;
end
end
% create cdf
cdf = cumtrapz(Phi, P);
% keep only the unique values: needed for interpolation
idx_mid = (Phi < pi) & (Phi >= -pi);
cdf = cdf(idx_mid);
Phi = Phi(idx_mid);
P = P(idx_mid);
% number of required random draws
n = 1e4;
% generate uniformly distributed random numbers from [0,1]
r = rand(n,1);
% generate random numbers from the desired pdf; inverse transform sampling
laplrnd = interp1(cdf, Phi, r);
% Verfication plot
[f,x] = hist(laplrnd,100);
bar(x,f/trapz(x,f))
hold on
plot(Phi, P, 'red', 'Linewidth', 1.2)
legend('histogram from random values', 'analytical pdf')
这篇关于给定PDF生成随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!