monte carlo simulation in matlab two dices roll
4 次查看(过去 30 天)
显示 更早的评论
if 2 dices were thrown & there top value were added ,what is the probability of getting a sum of 7 ?
5 个评论
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
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
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);
0 个评论
更多回答(1 个)
Md Jilani
2019-7-15
Hello sir, Good Day. How can I get probabilty from here ?
1 个评论
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!