
Help with Coin Toss Probability and if statements
4 ビュー (過去 30 日間)
古いコメントを表示
I am writing a code that will create a random number, where if it is <0.5 it is heads, and if it is >0.5 it is tails. Now I want this to run on loop with different random numbers until the absolute different between them is 12. Here's my code:
m = rand;
Heads = 0;
Tails = 0;
if m < 0.5
Heads = Heads + 1;
end
if m > 0.5
Tails = Tails +1;
end
if abs(Heads - Tails) == 12
disp ('Reached our number!')
end
if Heads > Tails
disp ('Heads wins!')
elseif Tails > Heads
disp ('Tails wins!')
end
Now the problem is that I want just the first 3 if's to run until there is a difference of 12, and THEN move on to the last 2 if's. Last thing, I don't know if this is possible but I don't want to have to limit myself to a certain number of terms. I want it to run for as long as it needs to until this happens. Any help would be MUCH appreciated!
0 件のコメント
回答 (1 件)
Image Analyst
2018 年 12 月 4 日
No looping needed. Do it vectorized by using rand() to do lots of tosses at once. Actually you should use randi() and save a step, but I'm using rand() like you did to show you how to do thresholding.
% Try a small number, and leave off semicolons, to see what the commands do.
% N = 10;
% Try a large number, and use semicolons, to make sure you can get a diff of 12.
N = 500;
r = rand(1, N); % N coin tosses
numHeads = cumsum(r > 0.5);
numTails = (1:N) - numHeads;
countDiff = abs(numHeads - numTails);
numTosses = find(countDiff >= 12, 1, 'first')
% Plot the count difference as a function of number of tosses.
plot(countDiff, 'b-');
grid on;
xlabel('Toss #', 'FontSize', 15);
ylabel('Diff between #heads and #tails', 'FontSize', 15);
% Put a line across at 12
hold on;
line(xlim, [12, 12], 'Color', 'r');
caption = sprintf('Passed 12 at %d tosses', numTosses);
title(caption, 'FontSize', 15);

0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Entering Commands についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!