如何在MATLAB中使用以下分布在[a,b]中生成整数随机数:
p(x)= x ^( - a) 我希望将分发规范化。
答案 0 :(得分:1)
连续发布:Generate random values given a PDF
对于离散分布,稍后在OP中指定
可以使用与连续分布相同的基本原理:inverse transform sampling。
因此从数学的角度来看没有区别,但Matlab的实现却有所不同。以下是您的分配功能的简单解决方案:
% for reproducibility
rng(333)
% OPTIONS
% interval endpoints
a = 4;
b = 20;
% number of required random draws
n = 1e4;
% CALCULATION
x = a:b;
% normalization constant
nc = sum(x.^(-a));
% if a and b are finite it is more convinient to have the pdf and cdf as vectors
pmf = 1/nc*x.^(-a);
% create cdf
cdf = cumsum(pmf);
% generate uniformly distributed random numbers from [0,1]
r = rand(n,1);
% use the cdf to get the x value to rs
R = nan(n,1);
for ii = 1:n
rr = r(ii);
if rr == 1
R(ii) = b;
else
idx = sum(cdf < rr) + 1;
R(ii) = x(idx);
end
end
%PLOT
% verfication plot
f = hist(R,x);
bar(x,f/sum(f))
hold on
plot(x, pmf, 'xr', 'Linewidth', 1.2)
xlabel('x')
ylabel('Probability mass')
legend('histogram of random values', 'analytical pdf')
注意:
a
也出现在分布函数和区间中。