function s = tangent(Func, x0, tol, max)
%
%TANGENT   Find a zero of a nonlinear equation of one variable 
%          using the tangent algorithm. Func is the name of an 
%          M-file that contains a real-valued function of a 
%	   single real variable, and x0 is the initial guess. 
%          Note that a poor initial quess may cause divergence.
%	   
%	   An optional third argument sets the tolerance for the
%	   convergence. The presence of an optional fourth 
%	   argument specifies the maximum iteration number.
%

% pre-processing, set default tolerance and maximum iteration
% number
%
if nargin<4, tol=0.000001; max=1000; end
if nargin==4, max=1000; end
t=[1:max]';

%
% start the tangent algorithm
%
for i=1:max,
    x1 = x0+ .001*x0;
    x2(i) = x0 - (feval(Func,x0)*(x1-x0))/(feval(Func,x1)...
          -feval(Func,x0));
    if(abs(x2(i)-x0) < tol)
	iteration = i
	T = x2(i)
	t = [1:iteration]';
	break;
    end
    x0 = x2(i);
end
%
% plot to see the convergence/divergence of the process
%
plot(t, x2, '-');
title('Convergence/Divergence of the Tangent Algorithm')
xlabel('iteration number')

%
% examples of calling this function:
%
%	>> tangent('cp1', 400)
%	>> tangent('cp1', 400, 0.000001)
%	>> tangent('cp1', 400, 0.000001, 1000)
%
% all these function calls in Matlab gives following results:
%
%	T = 443.5712
%	iteration = 5
%
% together with a graph window.
