Probability of exactly one even number
2 次查看(过去 30 天)
显示 更早的评论
Problem: Given n number of dice to throw, find the probability that in a single throw of the dice there is exact one even number. You cannot use any vectors or matrices, or any vectorized operations. Instead, use a double for-loop (one over the different trials, and another one for the different number of dice used).
I am confused on how to make sure that there is only one even number per trial.
1 个评论
Torsten
2019-4-4
You might want to compare your Monte-Carlo simulation results with the "correct" value for the probability.
It is given by P = n * 0.5^n.
采纳的回答
Image Analyst
2019-3-31
Very close but you need to check if just one even number was thrown OUTSIDE the inner loop over j. Also, a tip: to determine if something is even you can use rem(value, 2) rather than all that dividing stuff you're doing. Try this:
clear;
clc;
nDice = 3; % Number of dice
nTrials = 1e6; % Number of trials
singleCount = 0; % Count of how many trials have 1 even number
for i = 1:nTrials
% For this trial, initialize the number of even numbered dice thrown.
evenNumberCount = 0;
% Make nDice throws detecting if the throw was an even number.
for j = 1 : nDice
thisDicesValue = randi(6);
evenNumberCount = evenNumberCount + (rem(thisDicesValue, 2) == 0);
end
% See if only ONE of those throws was an even number during this trial.
if evenNumberCount == 1
% Only one even number was thrown
singleCount = singleCount + 1;
end
end
prob = singleCount / nTrials
fprintf('Found %d experiments where exactly 1 die in %d throws of %d dice had one even number.\n',...
singleCount, nTrials, nDice);
and adapt as needed.
0 个评论
更多回答(1 个)
Jos (10584)
2019-3-31
I suggest you use two counters: one counting the numbers of even values in a single throw, and one counting the number of throws that contain a single even number. The first one you need to reset to 0 before every throw. The later one you need to update by 1 if the first one is 1 after the throw-loop
Additional remarks:
- take a look at the function REM: rem(X, 2) == 0 is true for an even value of X
- this question is best answered using arrays and can even be handled by a one-liner
Prob = sum(sum(rem(randi(6, nTrials, nDice), 2) == 0, 2) == 1)) / nTrials
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!