function [x,X] = bisectdemo(f, int, tol)
% bisectdemo - bisection algorithm for the scalar equation f(x) = 0
% 
%   Syntax: 
%           [x,X] = bisectdemo(f, int, tol)
%   Arguments: 
%           f - function handle pointing to a function file  
%           int - 1x2 matrix specifying an interval int = [a,b]
%           tol - a tolerance 
%   Returns: 
%           x, X - column vectors containing the left and right endpoints 
%           of the bisected intervals
%   Description:
%           The program bisectdemo 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. 
%   Examples: 
%          [x,X] = bisectdemo(@sin,[1,4],1e-7)   computes pi to 7 decimals
%
%----------------------------------------------------------------------

i=1;
x(i)=int(1);
X(i)=int(2);

if f(x(i))*f(X(i))>0
  disp('Bisection fails: f(a), f(b) have the same sign.')
  x=[];
  X=[];
  return
end

while X(i)-x(i)>tol

  xx=(x(i)+X(i))/2;             % compute midpoint xx of current interval
  fx=f(xx);                     % evaluate f at midpoint

  if fx==0                          % root
    x(i+1)=xx;                
    X(i+1)=xx;                
  elseif f(x(i))*fx<0               % root in the left half 
    x(i+1)=x(i);                
    X(i+1)=xx;                
  else
    X(i+1)=X(i);                
    x(i+1)=xx;                
  end 
  
  i=i+1;
  
end 

x=x';
X=X';
