How do I create a random number generator using congruent method
显示 更早的评论
I want to create a random number generator that uses a congruent method. And I need to create a histogram that should have 0.2 for 1, 0.4 for 2 and 0.4 and 3. When I use rand the histogram works right.
The code I used was this:
prod_total = [];
for j = 1:1000
x0 = 4;
m = 5;
vetor_aleatorio = [ ];
for k = 1:100
[u1, x0] = n_aleatorio(x0, k, m);
vetor_aleatorio(k) = u1;
end
x = rand;
if (x <= 0.2)
prod = 1;
elseif (x > 0.2 & x <= 0.6)
prod = 2;
elseif (x > 0.6 & x <= 1)
prod = 3;
end
prod_total = [prod_total, prod];
end
histogram(prod_total)
采纳的回答
更多回答(1 个)
If this is not for a homework assignment, either use one of the existing random number generators in MATLAB (as listed on this documentation page the 'mcg16807' generator is a multiplicative congruential generator, though it has a very short period) via the rng function or use discretize to convert the uniform numbers from a call to rand into your desired distribution.
weights = [0.2, 0.4, 0.4];
breakpoints = cumsum([0, weights]);
breakpoints(end) = 1;
uniformData = rand(1, 1e6);
discretizedData = discretize(uniformData, breakpoints);
histogram(discretizedData, Normalization="probability");
yline([0.2 0.4], 'r:')
Those look in pretty good agreement with the weights vector.
类别
在 帮助中心 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
