monte carlo simulation in matlab two dices roll

19 ビュー (過去 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 Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by