% Eg2_2.m
% Pi Via Polygons
%
%  Consider a circle of unit radius, whose area is Pi.
%  Put an N-sided polygon inside the circle, of area An, 
%  Put an N-sided polygon around the circle, of area Bn.
%  Then An <= Pi <= Bn.
%
%  Increase N until Bn-An is smaller than some tolerance.
%
%  Let the user choose the tolerance, and the maximum number of sides.
%
delta = input ( 'Enter the error tolerance:' );
nMax  = input ( 'Enter the iteration bound:' );
%
%  Initialize by approximating the circle with triangles.
%
n = 3;                        % Number of sides
A_n = (n/2)*sin(2*pi/n);      % Area of inside triangle
B_n = n*tan(pi/n);            % Area of outside triangle
ErrorBound = B_n - A_n;       % Maximum error in PI estimate.
%
%  As long as:
%    Our estimated error is bigger than the tolerance
%  AND
%    Our value of N hasn't reached the maximum allowed
%
while ( ErrorBound  > delta  && n < nMax )
  n = n+1;
  A_n = (n/2)*sin(2*pi/n);
  B_n = n*tan(pi/n);
  ErrorBound = B_n - A_n;
end
%
%  Our iteration has stopped.  Report the results.
%
estimate = (A_n + B_n)/2;
fprintf(' delta = %10.3e\n nStar = %1d\n nMax  = %1d\n\n',...
                                               delta,n,nMax)
fprintf(' rho_nStar = %20.15f\n Pi        = %20.15f\n',...
                                                   estimate,pi)


