% Function Secant
%
% x0, x1 : two initial estimations of the root
% acc : digits of the required accuracy
% f  : the function, f(root) ~= 0 
% root : the root
% no_fun : number of function evaluations
% tot : total number of repetitions
%
function [root,no_fun,tot] = secant(x0, x1, acc, maxiter, f)

filename = ['results_secant_' f '.dat'];
fout = fopen(filename, 'w+');
fprintf(fout, ' Iter \t || \t x(k) \t|| \t f(x(k)) \t || |x(k)-x(k-1)| \n');   

no_fun = 0;
accur=0.5*10^(-acc);

k=1;
x(k) = x0;
fx(k) = feval(f,x(k));
no_fun = no_fun + 1;
fprintf(fout, ' %5g \t || %10.5f || %10.5f || --- \n',k,x(k),fx(k));

k = 2;
x(k) = x1;
fx(k) = feval(f,x(k));
no_fun = no_fun + 1;
dif = abs(x(k)-x(k-1));
fprintf(fout, ' %5g \t || %10.5f || %10.5f || %10.5f \n',k,x(k),fx(k),dif);

while ( k <= maxiter )

    k = k + 1;
    x(k) = x(k-1) - fx(k-1) * (x(k-1) - x(k-2))/(fx(k-1)-fx(k-2)); %epanaliptiko sxima
    fx(k) = feval(f,x(k));
    no_fun = no_fun + 1;
    
    dif = abs(x(k)-x(k-1));
    
    fprintf(fout, ' %5g \t || %10.5f || %10.5f || %10.5f \n',k,x(k),fx(k),dif);
    
    if ( (dif <= accur) && (abs(fx(k)) <= accur) ) %kritiria termatismou
        
        root = x(k);
        tot = k;
        fprintf(fout, ' The root is calculated after %5g iterations and it is: %10.5f \n', tot,root);
        fprintf(fout, ' Number of function evaluations = %5g \n', no_fun);
        break;
        
    end
    
end

fclose('all')

% Plot the graphical description of Secant
%graph(x,fx,'f') 

end
 
    


        
        
        
        
        
        
        