%% Script File: ShowBisect
% C van Loan, modified by HA 26.1.2014
% Illustrates 6 steps of the method of bisection.

close all
% Poistetaan kyselyt
%fName   = input('Enter the name of the function (in quotes):');
%a0      = input('Enter the left  endpoint of interval of interest:');
%b0      = input('Enter the right endpoint of interval of interest:');

%% Esim:
fName=@sin
a0=pi/2; b0=3*pi/2;   % Alkuvali
%%
close all
x = linspace(a0,b0);
y = fName(x);
figure
plot(x,y,x,0*x);
grid on
hold on
title('Click in left endpoint a.');
[a,y] = ginput(1);
plot(a,y,'*')
title('Click in right endpoint b.');
[b,y] = ginput(1);
hold on
plot([a b],[0 0],'*')
% Display the initial situation.
x  = linspace(a-.1*(b-a),b+.1*(b-a));
y  = fName(x);
fa = fName(a); 
fb = fName(b);  
plot(x,y,x,0*x,[a b], [fa fb],'*')
grid on
xlabel(sprintf('At the start:    a = %10.6f   b = %10.6f',a,b));
for k=1:6
   mid = (a+b)/2;
fmid = fName(mid);  
   title('Strike any key to continue');  
   disp('Strike any key to continue');  
   pause
   if fa*fmid<=0
      % There is a root in [a,mid].
      b  = mid; 
      fb = fmid;
   else
      % There is a root in [mid,b].
      a  = mid; 
      fa = fmid;
   end   
   x = linspace(a-.1*(b-a),b+.1*(b-a));
y = fName(x);
   figure
   plot(x,y,x,0*x,[a b], [fa fb],'*')
   grid on
   xlabel(sprintf('After %1.0f steps:     a = %10.6f      b = %10.6f',k,a,b));
end 
format long
['keskiarvo = ',num2str(mid)]
format