% LMex060301_4th.m
% page 444-445 in
% Larsen & Marx (2006) Introduction to Mathematical Statistics, 4th edition
% Written by Eugene.Gallagher@umb.edu, 2003, revised 3/8/11
p=0.85;
n=19;
alpha=0.2;
Expected=p*n
k=0:19;
pdf=binopdf(k,n,p);
i=find(k<Expected);
fprintf(...
    'Goal is to find 2-tailed critical values for alpha=%4.2f\n',...
    alpha);
cpdf=cumsum(pdf(i));
disp(['k             ';'pdf           ';'cumulative pdf'])
disp([k(i);pdf(i);cpdf]);
j=max(find(cpdf<=alpha/2));
if cpdf(j)~=alpha/2
    j=j+1;
end
fprintf('The lower critical value is %d with cumulative pdf of %6.4f\n',...
    k(i(j)),cpdf(j));
fprintf('Find the upper critical value\n')
i=find(k>Expected);
ucpdf=fliplr(cumsum(fliplr(pdf(i))));
disp([k(i);pdf(i);ucpdf]);
m=min(find(ucpdf<=alpha/2));
if isempty(m);
    fprintf('There is no upper critical value\n')
else

% By inspecting the cumulative pdf, the goal of attaining a nearly
% symmetric set of critical values around the expected values is 
% met by setting the upper critical value at 19
fprintf('The upper critical value is %d with cumulative pdf of %6.4f\n',...
    k(i(m)),ucpdf(m));
fprintf('With these critical values & Ho: p=%4.2f, P(Type I error)=alpha=%6.4f\n',...
    p,ucpdf(m)+cpdf(j))
end