MATLAB: Suppose you repeatedly flip a coin and keep track of the number of times
ID: 3727738 • Letter: M
Question
MATLAB: Suppose you repeatedly flip a coin and keep track of the number of times you get heads. How many flips will it take before you get twenty heads? thirty heads? one hundred heads? You probably have an idea of what the answers should be. In this problem, you will model flipping a coin using MATLAB's randperm function and determine the average number of coin flips experimentally.
a. Write a function named flipUntil that takes one parameter, numHeads, repeatedly flips a coin until a heads has been seen numHeads times, and returns the number of flips needed to get numHeads heads. You may assume that numHeads is a single non-negative integer.
The first line of your flipUntil function should be:
The flipUntil function must use a while loop.
b. If you run your flipUntil several times with the same value for the input parameter, you will find that you get different results each time. Suppose we consider one call to flipUntil to be a single trial.
Write a code fragment that asks the user for the number of heads and runs 2000 trials and then displays the average number of flips needed to get that number of heads. (Hint: you will need to use a 'for' loop.) You may assume that the user always enters a single non-negative integer when prompted for the number of heads.
Explanation / Answer
(a)
code for matlab:-
count = 0;
coinsFlipped = 0;
while count <= 30
coin = randi(2);
% 2 is assumed as tail and 1 as head
if coin == 1
count = count + 1;
end
coinsFlipped = coinsFlipped + 1;
end
fprintf('Number of coins flipped to get 30 heads: %d ',coinsFlipped);
executed output:-
Number of coins flipped to get 30 heads: 79
(b)
code:-
totalCoinsFlipped = 0;
for i=1:2000
count = 0;
coinsFlipped = 0;
while count <= 30
coin = randi(2);
% 2 is assumed as tail and 1 as head
if coin == 1
count = count + 1;
end
coinsFlipped = coinsFlipped + 1;
end
totalCoinsFlipped = totalCoinsFlipped + coinsFlipped;
end
average = totalCoinsFlipped/2000;
fprintf('Average Number of coins flipped to get 30 heads: %d ',average);
output:
Average Number of coins flipped to get 30 heads: 61.9895
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.