monte carlo simulation in matlab two dices roll

조회 수: 30 (최근 30일)
isuru senevirathne
isuru senevirathne 2018년 5월 11일
편집: Jan 2019년 7월 15일
if 2 dices were thrown & there top value were added ,what is the probability of getting a sum of 7 ?
  댓글 수: 5
Jeff Miller
Jeff Miller 2018년 5월 13일
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 2018년 5월 13일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2018년 5월 13일
편집: Jan 2019년 7월 15일
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);

추가 답변 (1개)

Md Jilani
Md Jilani 2019년 7월 15일
Hello sir, Good Day. How can I get probabilty from here ?
  댓글 수: 1
Jan
Jan 2019년 7월 15일
편집: Jan 2019년 7월 15일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by