monte carlo simulation in matlab two dices roll

14 visualizaciones (últimos 30 días)
isuru senevirathne
isuru senevirathne el 11 de Mayo de 2018
Editada: Jan el 15 de Jul. de 2019
if 2 dices were thrown & there top value were added ,what is the probability of getting a sum of 7 ?
  5 comentarios
Jeff Miller
Jeff Miller el 13 de Mayo de 2018
to count the number of 7's, use a counter variable, e.g., Ctr. Set it to zero before you start the loop, and then add one to it each time your sum equals 7. When the loop finishes, the value in Ctr will be the number of 7's that were found.
Image Analyst
Image Analyst el 13 de Mayo de 2018
isuru, here's a tip to format your code correctly. In MATLAB type control-a control-i to properly indent your code. Then copy it and paste it here. Highlight the code and then click the {}Code button. See this link
And note how Jan's properly formatted answer below does not use sum as the name of a variable so as to not override the built-in sum function.

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 13 de Mayo de 2018
Editada: Jan el 15 de Jul. de 2019
n = 10; % Number or trials
throw = randi(6, n, 2); % Value of throws, 2 dice
SumThrow = sum(throw, 2); % Sum of both dice
Match = (SumThrow == 7); % Logical array: 1 if sum of values is 7
count = sum(Match); % Number of matching throws
Or with modifications of your code:
count = 0;
for i=1:10
throws1 = randi(6, 1);
throws2 = randi(6, 1);
sumThrow = throws1 + throws2; % Do not use "sum" as name of a variable
if sumThrow == 7
fprintf('sum is 7\n')
count = count + 1;
else
fprintf('false\n')
end
end
fprintf('Number of throws with sum=7: %d\n', count);

Más respuestas (1)

Md Jilani
Md Jilani el 15 de Jul. de 2019
Hello sir, Good Day. How can I get probabilty from here ?
  1 comentario
Jan
Jan el 15 de Jul. de 2019
Editada: Jan el 15 de Jul. de 2019
Please do not post new questions in the section for answers. Prefer to open your own thread. Thanks.
My code counts the number of 7's in the variable count for n throws. Then the probability is approximately n / count.
You can determine the probability in a constructive way also:
nAll = 0;
n7 = 0;
for throw1 = 1:6
for throw2 = 1:6
nAll = nAll + 1;
if throw1 + throw2 == 7
n7 = n7 + 1;
end
end
end
n7 / nAll
Of course you can do this manually also, because the calculations are very easy: There are 36 possible throws with 2 dice. You get a sum of 7 for 1+6, 2+5, 3+4, 4+3, 5+2 and 6+1: 6 possibilities.

Iniciar sesión para comentar.

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by