function x=bisec(f,int,tol)
% bisec - bisection algorithm for the scalar equation f(x)=0
% 
%   Syntax: 
%           x = bisec(f,int,tol)
%   Arguments: 
%           f - string containing the name of a function file  
%           int - 1x2 matrix specifying an interval int=[a,b]
%           tol - a tolerance 
%   Returns: 
%           x - an approximate solution in the interval int=[a,b]
%   Description:
%           The program bisec uses the bisection algorithm to 
%           compute an approximate solution of the scalar equation
%           f(x)=0 in the interval int=[a,b].  The file f.m must 
%           contain the function y=f(x).  The function values f(a) 
%           and f(b) must have opposite signs.  Then the program
%           computes an approximate solution x with the error
%           |x-x_exact| < tol.  It returns an empty value for x if
%           f(a) and f(b) have the same sign.  
%   Examples: 
%          x = bisec('sin',[1,4],1e-7)   computes pi to 7 decimals
%          x = bisec('funk1',[0,3],1e-7) computes the square root of 2
%   See also:
%          regula_falsi.m, fixpoint.m, newton.m
%

%----------------------------------------------------------------------
%   Bugs:
%
%   Date created: 
%          991017
%   Author:
%          Stig Larsson
%
%   Change history:
%
%                              +---------------------------------------+ 
%                              |     Matematik Kf/Kb 1999-2000         | 
%                              |     Copyright (c) 1999                | 
%                              |                                       | 
%                              |     Stig Larsson                      | 
%                              |     Mathematics                       | 
%                              |     Chalmers University of Technology | 
%                              |     SE-412 96 Göteborg                | 
%                              |     SWEDEN                            |     
%                              |     stig@math.chalmers.se             |     
%                              |     http://www.math.chalmers.se/~stig |     
%------------------------------+---------------------------------------+
a=int(1); b=int(2);        % endpoints of interval 
fa=feval(f,a);             % evaluate f at a 
fb=feval(f,b);             % evaluate f at b 

% stop if f(a) and f(b) have the same sign
if fa*fb>0                
  disp('bisec fails: f(a) and f(b) have the same sign')
  x=[];                    % empty value
  return                   % return from bisec
end

% if the program execution continues, 
% then let c,d be points such that f(c)<0 and f(d)>0 
if fa<0 
  c=a;
  d=b; 
else 
  c=b; 
  d=a;
end 

while abs(c-d)>tol 

  x=(c+d)/2;
   
  if feval(f,x)<0 
    c=x;
    d=d; 
  else 
    c=c; 
    d=x;
  end 

end 

x=(c+d)/2;

