A09.m - Approximating pi to desired accuracy (using a for loop with a break)

% 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

% 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')
    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)

Download A09.m

This code is very similar to A07.m, but it uses a for loop with a break instead of a while loop. In this example, the program set a maximum nuber of iterations, and prints an error message if that number is exceeded. Sometimes this can be useful to prevent infinite loops.

Monkey Home   |    Prev   |   Next