Making relative histogram for data, and a convergence diagram to see if enough trials have been run for monte carlo simulation.

1 次查看(过去 30 天)
I have written a monte carlo code for a double dice throw that calculates the probability of the throw sum being 8 or over 8. I have to make a relative frequency histogram for the sum of the dice with 11 bins. And show a convergence diagram to show that enough trials have been done. I do not know which part of my code to plot into the histogram to make a relative frequency histogram. I also do not know how to make a convergence diagram to show enough trials were done.
count = 0;
for i=1:1000;
throwD1 = randi(6, 1);
throwD2 = randi(6, 1);
Throwsum = throwD1 + throwD2;
if Throwsum >=8
fprintf('Sum>=8');
count = count + 1;
else
fprintf('Sum<8');
end
end
fprintf('Number of throws with sum=7: %d\n', count);
nAllruns = 0;
n8 = 0;
for throwD1 = 1:6
for throwD2 = 1:6
nAllruns = nAllruns + 1;
if throwD1 + throwD2 >= 8
n8 = n8 + 1;
end
end
end
prob=n8 / nAllruns

采纳的回答

Alan Stevens
Alan Stevens 2021-7-3
Something like the following?
N = 1000;
Throwsum = zeros(N,1);
Relativefreq = zeros(N,1);
count = 0;
for i=1:1000
throwD1 = randi(6, 1);
throwD2 = randi(6, 1);
Throwsum(i) = throwD1 + throwD2;
if Throwsum(i) >=8
count = count + 1;
end
Relativefreq(i) = count/i;
end
figure
histogram(Throwsum,11);
xlabel('Sum of two dice'), ylabel('Frequency')
figure
plot(1:N,Relativefreq),grid
xlabel('trials'),ylabel('Prob sum >= 8')
fprintf('Relative number of throws with sum >= 8: %d\n', count/N);
Relative number of throws with sum >= 8: 4.110000e-01

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Histograms 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by