%
% A09.m
%
% Use the Madhava-Leibniz series method to approximate pi
%
% Programming Concepts:  for loop with break, includes error handling
%
% 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
max_iter = 1000;    % maximum number of iterations allowed
s = 0;              % this initializes the sum to 0

for n = 0:max_iter
    s = s + sqrt(12) * (-1/3)^n/(2*n+1);     %Madhava-Leibniz series

    if abs(s-pi) < tol      % if desired tolerance is reached, break out of loop 
        break;
    end
end

% check to see if the loop reached the maximum nuber of iterations before
% reaching the desired tolerance. If yes, the print an error message,
% otherwise print the results of the series approximation
if n == max_iter
    disp('ERROR:  reached maximum # iterations before reaching desired tolerance')
else
    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)
end