Probability of exactly one even number

1 vue (au cours des 30 derniers jours)
Winnie Tsui
Winnie Tsui le 31 Mar 2019
Commenté : Torsten le 4 Avr 2019
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 commentaire
Torsten
Torsten le 4 Avr 2019
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.

Connectez-vous pour commenter.

Réponse acceptée

Image Analyst
Image Analyst le 31 Mar 2019
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.

Plus de réponses (1)

Jos (10584)
Jos (10584) le 31 Mar 2019
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

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by