Skip to main content

Section 4.2 while loop

In Example 4.1.2 we used 10 iterations of arithmetic and geometric means computation. This was an arbitrary number. For some input values it may be enough or too many, for others not enough. A better approach is to stop the computation when the required precision is achieved. If we want the result to be accurate within \(10^{-9}\text{,}\) which is 1e-9 in Matlab notation, then we can stop as soon as the difference between the two means has absolute value less than that number (called the tolerance). This is what while loop can be used for.

Syntax of while loop:

while (some condition) 
    (some computation)
end

The loop will repeat while condition after while is true. It ends when this condition becomes false. So, if we want to stop when abs(x-y) < 1e-9, the loop should be written as while abs(x-y) >= 1e-9.

Find the arithmetic-geometric mean (AGM) of two numbers given by a user, with 1e-9 accuracy.

Answer
x = input('x = ');
y = input('y = ');
while abs(x-y) >= 1e-9
    a = (x+y)/2;
    g = sqrt(x*y);
    x = a;
    y = g;
end
fprintf('AGM(x, y) = %.9f\n', x)

There are two common issues with using while loops. One is that it can go on forever, if the algorithm fails to reach its goal (the difference never becomes smaller than the tolerance). It is better to admit that the algorithm failed than to be stuck in an infinite loop: we will deal with this in Section 4.3. For now, note that if your program gets stuck in an infinite loop, you can terminate it by clicking within the Command Window and pressing Ctrl+C.

Another issue is that the condition we want to test may not be defined at the beginning of the loop. This occurs when our condition for stopping is that the value of a variable essentially stopped changing. For example, one way to compute the golden ratio numerically is to start with any \(x > 0\) and keep replacing \(x\) with \(\sqrt{x+1}\text{.}\) If we write this as:

x = 1;
while abs(newx - x) >= 1e-9
    newx = sqrt(x+1);
    x = newx;
end
fprintf('Golden ratio = %.9f\n', x)

the result will be an error: “Undefined function or variable ‘newx’” because we attempt to compute an expression with newx before it is defined. Here is one way to correct this.

x = 1;
dx = 1; 
while abs(dx) >= 1e-9
    newx = sqrt(x+1);
    dx = newx - x;
    x = newx;
end
fprintf('Golden ratio = %.9f\n', x)

Here we introduce a variable dx that represents the difference between old and new values of x. This variable can be initially assigned some arbitrary value that is greater than the tolerance, for example 1 or 100. This ensures that the condition abs(dx) >= 1e-9 holds at the beginning of the loop. After that the loop changes the value of dx and the process repeats until it becomes small enough.