A07.m - Approximating pi to desired accuracy (using a while loop)

% 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 counter
    s = s + sqrt(12) * (-1/3)^n/(2*n+1);    %Madhava-Leibniz series

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 A07.m

Typically, a for loop will execute a predetermined number of iterations. However, there are situations when you don't know how many times you need to iterate the loop. Consider, for example, the case where you want to approximate pi by calculating a finite number of terms of in infinite series. If you want to calculate pi to some desired accuracy, you might not know how many terms to keep in the series ahead of time. Thus, you would want to keep adding terms while the error is larger than some set value. Such a loop is called a while loop. The loop keeps going while some condition is true. Once the condition becomes false, then the loop stops.

In the code above, the condition of the while loop is that the error is greater than a specified tolerance tol. The error is equal to the sum of the terms in the series s minus the actual value of pi. While the error is larger than the specified tolerance, the while loop keeps calculating new terms. Once the error drops below or equal to the tolerance, the while loop stops and the approximate value of pi is displayed to the screen along with the number of terms that were needed.

Monkey Home   |    Prev   |   Next