% Script: PolygonPi
% Computes Pi by computing the areas of regular n-gons
% that inscribe and circumscribe the unit circle.

% Key variables...

% n = the number of sides. 
% InnerArea = (n/2)*sin(theta), the area of the inner polygon
%              where theta = 2pi/n
% OuterArea = n*tan(theta/2), the area of the outer polygon
%              where theta = 2pi/n
% c = cos(theta)
% s = sin(theta)
% t = tan(theta/2)

% The triangle case...
n = 3;                  
InnerArea =  3*sqrt(3)/4;   
OuterArea =  3*sqrt(3);     
c  = -1/2;  

% Iteration parameters...
nMax = 1000000;          % Upper bound for n
tol  = .000001;          % Compute pi to this accuracy
clc
% Iterate while error too big and n sufficiently small...
while (OuterArea-InnerArea > tol)  && (2*n < nMax)
    % Double n and compute the inner and outer areas...
    n = 2*n;
    s = sqrt((1-c)/2);      % sin(2*pi/n)
    c = sqrt((1+c)/2);      % cos(2*pi/n)
    t = sqrt((1-c)/(1+c));  % tan(pi/n)
    InnerArea = (n/2)*s;              
    OuterArea = n*t;           
    fprintf('\nn = %6d  Inner = %11.7f\n            Outer = %11.7f\n',n,InnerArea,OuterArea)
end
