
probability of sum of dice rolling n times
조회 수: 2 (최근 30일)
이전 댓글 표시
I have trouble with me homework.
so the problem is this: i have n fair dices with 6 sides that roll all together and i need to calculate the probability of sum of dices side.
i need to write script when:
function prob = sumDicePDF(n,k)
input: 1. number of dices(n >= 1) 2. k - integer number from n to 6n
output: probability
example: sumDicePDF(3,4) ans = 0.0139 sumDicePDF(8,20) ans = 0.0218
i need to use equalition: probability = sigma[1:6](P(sum(n-1) = k - i) * 1/6
and i forbiden to use recursion so my script run time must be near n^2
i understood the problem but i cant find a way to biuld the loop for counting probability so my answer be prob=(1/6)^n*sumOfCounting;
so my quastion is how to make loop to find sumOfCounting.
i wrote:
vec = ones(1,n - 1);
sumOfCounting = 0;
for i = 1:6
for j = 1:length(vec)
vec(j) = i;
sumOfvalue = sum(vec);
if k - sumOfvalue < 7 && k - sumOfvalue > 0
for m = 1:length(vec)
sumOfCounting = sumOfCounting + length(vec) + 1 - m;
end
end
end
end
but it not counting all options so where is the problem?
thank and best wishes.
댓글 수: 0
채택된 답변
Image Analyst
2013년 5월 25일
Nice try, but why not just use the sum() function - that's what it's there for:
% Roll the dice "numberOfRolls" times
numberOfRolls = 200; % Number of times you roll all 6 dice.
n = 10; % Number of dice.
maxFaceValue = 6;
rolls = randi(maxFaceValue, n, numberOfRolls)
% Sum up dice values for each roll.
columnSums = sum(rolls, 1)
% Find out how many times each sum occurred.
edges = min(columnSums):max(columnSums)
counts = histc(columnSums, edges)
% Normalize
grandTotalSum = sum(counts(:))
normalizedCountSums = counts / grandTotalSum
bar(edges, normalizedCountSums, 'BarWidth', 1);
grid on;
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
title('Frequency of Roll Sums', 'FontSize', 40);

댓글 수: 5
Image Analyst
2013년 5월 30일
With lots of nested for loops, it doesn't look as efficient as mine, which I timed at 0.001 seconds, but whatever ... it's only 3 milliseconds (not noticeable at all) and it's your homework and if you understand yours better that's fine. At least I introduced you to a vectorized, fast way of doing it.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!