% Flip a coin n times, see how close we come to the expected fraction of
% heads.

reps=10000 % Number of repetitions of the experiment
n=100 % Number of flips per experiment
p=.5 % Probability of heads

headfrac=NaN(reps,1); % Get ready to record the results
for k=1:reps
    flips=rand(1,n)<p;
    total=sum(flips);
    headfrac(k)=total/n;
end

figure(1)
hist(headfrac,p-.2:.01:p+.2)

figure(2)
plot(sort(headfrac))

% What fraction of experiments gets us close to p?
tolerance = .1
successes = sum(headfrac>=(p-tolerance) & headfrac<p+tolerance)
successfrac= successes / reps