% square_root2.m
%
%  Estimate the square root of a number.
%  Use a BREAK statement to terminate the loop early if the error is low.
%
%  We'll say the error is low enough if X and Y are closer than 100*eps.
%
%  We require X*Y = Z
%  and we try to "encourage" x=y.
%
z = input ( '  Enter Z, whose square root is desired:' );
%
%  Initialize, so that X*Y = Z
%
x = z;
y = z / x;
%
%  Repeat the following steps up to N=20 times.
%
n = 20;
for i = 1 : n
%
%  Replace X and Y by average.
%  Set Y so that it's still true that X*Y = Z.
%
  x = ( x + y ) / 2.0;
  y = z / x;
%
%  A BREAK statement allows us to finish early, if we are
%  already satisfied with the results.
%
  if ( abs ( x - y ) < 100.0 * eps )
    n = i;
    fprintf ( '  Terminate early, on step %d\n', n );
    break
  end

end
%
%  Print results.
%
fprintf ( '  %g * %g = %g, %d steps, exact square root is %g\n', ...
  x, y, z, n, sqrt ( z ) );

