MATLAB: Probability of exactly one even number

for loophomeworkMATLABmonte carloprobability

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.

Best Answer

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.