function [x0,it] = bisect(fun,a,b,tol)
% [x0,it] = bisect(fun,a,b,tol)
%
% funkce nalezne minimum funkce f(x)
% na intervalu <a,b> metodou puleni intervalu
%
% x0 ... minimum
% it ... pocet iteraci
%
% fun ... f(x) zadana ve stringu 
% a,b ... meze intervalu
% tol ... pozadovana absolutni presnost


an = a;
bn = b;
fan = feval(fun,an);
fbn = feval(fun,bn);

cn=(an+bn)/2;
fcn=feval(fun,cn);

if (fan<=fcn) & (fbn<=fcn)
   error('funkce neni v intervalu <a,b> unimodularni')
end


it = 0;

while (bn - an) >= tol 
   a=an; b=bn; c=cn;
   fa=fan; fb=fbn; fc=fcn;
   
   d=(a+c)/2;
   fd=feval(fun,d);
   
   e=(c+b)/2;
   fe=feval(fun,e);
     
   if (fd<=fc)
      an=a; bn=c; cn=d;
      fan=fa; fbn=fc; fcn=fd;
   elseif (fc<=fd) & (fc<=fe)
      an=d; bn=e; cn=c;
      fan=fd; fbn=fe; fcn=fc;
   elseif (fe<=fc)
      an=c; bn=b; cn=e;
      fan=fc; fbn=fb; fcn=fe;
   else
      error('funkce neni v intervalu <a,b> unimodularni')
   end;
   
   it = it + 1; 
end

x0 = cn;

% end