%
% A07.m
%
% Use the Madhava-Leibniz series method to approximate pi
%
% Programming Concepts:  while loop
%
% INPUT:    User is prompted to enter the desired tolerance
% OUTPUT:   the approximate value of pi and the number of terms used in the
%           series are displayed to the command window
%
% Matlab-Monkey.com
% 12/30/2014

% tidy-up your workspace
clc         % clear command window
clear       % clear all variables
close all   % close all graphics windows

% get info from user
fprintf('Approximating pi using the Madhava-Leibniz series\n')
tol = input('Desired tolerance:  ');


% initialize variables for the loop
n = 0;                  % n counts the terms in the series
s = sqrt(12);           % this initializes the sum to the first term (n=0)
                        % in the series

while abs(s-pi) > tol   % while loop starts with the second (n=1 term) and
                        % goes until sum (s) converges to within tol of 
                        % the true value
                        
    n = n + 1;          % increment the number counter
    s = s + sqrt(12) * (-1/3)^n/(2*n+1);    %Madhava-Leibniz series
end

fprintf('\n')
fprintf('approximate value of pi = %.15g\n',s)
fprintf('     actual value of pi = %.15g\n\n',pi)

fprintf('number of terms in the series = %i\n',n)