function [results, ave_value, rel_unc] = coin_toss (ntrials);

% coin toss experiment
%
% [results, ave_value, rel_unc] = coin_toss (ntrials);
%
% 1. rand returns a number from a pseudo-random sequence 
%    based on a uniform distribution
% 2. coin toss (two outcomes) simulation: let H be the
%    event that rand is in (0, 0.5), let T be the event that
%    rand is in (0.5, 1.0)
% 3. represent H by 1 and T by 0
% 4. results: array of the trial outcomes for 1:ntrials
% 5. ave_value: array of the expected values as a function of trial #
% 6. rel_unc: array of the relative uncertainty as a function of trial #

p = 0.5; % probability of Heads (or success)
for i=1:ntrials,
    toss = rand;
    if (toss > 0 & toss < p)
        results(i) = 1;
    elseif (toss > p & toss < 1)
        results(i) = 0;
    end
    ave_value(i) = sum(results)/i;
end

% calculate the standard deviation and relative uncertainty after each trial
for i=1:ntrials,
    if (i==1)
        std_dev(i) = 0; % undefined for a single data point
        rel_unc(i) = 0; % undefined for a single data point
    else
        std_dev(i) = sqrt(sum((results-ave_value(i)).^2)/(i-1));
        rel_unc(i) = std_dev(i)/(ave_value(i)*sqrt(i));
    end
end
%
% plot ave_value result vs. ntrials
%
plot(ave_value,'k*-')
axis([1,ntrials, 0,1])
xlabel('trial')
ylabel('average value')
grid
title_text = sprintf('average value of repeated coin toss: H=1, T=0, p=%5.3f',p);
title(title_text)
