% Coin flip experiment
% Make sure we are starting clean
clear
% Initialize the counters for heads and tails
h = 0; % heads
t = 0; % tails
% Get the number of times to flip the coin
n = input('number of flips: ');
% Start main flipping loop
for i = 1:n
% Simulate a flip using the random number generator
% This generates a number in the interval [0,1)
f = rand;
% If the coin is fair, then half the time it will be heads
% and half the time it will be tails. We can translate this to
% and if then condition by saying that if the value of the random
% number is less than 1/2. it is a head, otherwise it is a tail.
if (f < 0.5);
h = h + 1;
else
t = t + 1;
end
end
% Display the total results.
disp('heads')
h
disp('tails')
t
% Display the results as percentages. This is easier to interpret than
% raw counts
disp('Percentage of heads')
hpct = h/n
disp('Percentage of tails')
tpct = t/n