% MATLAB EXPLANATION
%
% Example 3 - WHILE LOOP
%
% There are two basic types of loops in programming, and MATLAB can execute
% both of them.
%
% One type of loop is the WHILE loop. The WHILE loop is used
% when a set of calculations is to be executed multiple times. In this
% case the number of times the iteration is to be performed is CALCULATED
% WITHIN THE LOOP.
% An example of the WHILE loop is the calculation of sin(x) using the
% Taylor series expansion:
%
% sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...
%
% This series converges, and the error is the particular term, a value
% which is calculated within the loop. So, a loop can be constructed
% which calculates the next term, and then stops if that term, the error
% of the sine function, is very small.
%
x = 5.43245;
target = 0.000000001;
sine = x;
term = x;
count = 3;
% x = the number (in radians) for which we are finding the sine.
% term = each subsequent term, and the error in the calculation.
% target = the (maximum) error in the calculation of sine.
% We initialized the value to be x (see series)
while abs(term)>target
term = -term*x*x/((count-1)*count);
sine = term + sine;
count = count+2;
end;
format long
sine
% Some other concepts were shared in this example.
%
% abs() = is a function which finds the absolute value of the argument.
%
% format long = indicates that the output format should be "long", which
% provides fifteen digits of output. Note that because of the value of the
% variable "target", the first nine digits of the sine calculation in this
% program are correct.