function Y = ex28()
% function file ex28.m. function: to allow subfunctions
% solve eqn. 1+cos(x)-exp(x) = 0
% in the interval [0,pi]
% with several methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
close all
clc
TOL = 0.000001; % stopping tolerance

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Bisection
tic;
  
x0 = 0;
x1 = pi;

differ = 10*TOL;
iter = 0; 

while differ>TOL
  iter = iter+1;
  xm = (x0+x1)/2;
  
  g0 = g(x0);
  g1 = g(x1);
  gm = g(xm);
  
  if g0*gm<0
    x0 = x0;
    x1 = xm;
  else
    x0 = xm;
    x1 = x1;
  end  
  differ = x1-x0;  
end

disp(sprintf('Bisection:    x = %1.10f',(x0+x1)/2));
disp(sprintf('              Iterations: %d',iter))
disp(sprintf('              Time: %1.5f',toc));
disp(' ')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Newton
tic;
x0 = 0;
differ = 10*TOL;
iter = 0;

while differ>TOL
  iter = iter+1;
  
  x1 = x0-g(x0)/gpr(x0);
  differ = abs(x1-x0);
  
  x0 = x1;
end
disp(sprintf('Newton:       x = %1.10f',x1));
disp(sprintf('              Iterations: %d',iter))
disp(sprintf('              Time: %1.5f',toc));
disp(' ')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Regula Falsi
tic;

x0 = 0;
x1 = pi;

differ = 10*TOL;
iter = 0;

while differ>TOL
  iter = iter+1;
  x2 = x1 - (x1-x0)/(g(x1)-g(x0))*g(x1);
  differ = abs(x2-x1);
  x0 = x1;
  x1 = x2;
end
disp(sprintf('Regula Falsi: x = %1.10f',x2));
disp(sprintf('              Iterations: %d',iter))
disp(sprintf('              Time: %1.5f',toc));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = g(x)
  y = 1+cos(x)-exp(x);
  

function y = gpr(x)
  y = -cos(x)-exp(x);
  

  