%
%   RROOTS_1MAIN.M   Simple Root Finding Example for Lesson 5 Lecture Notes
%
%   -->  Consider the folowing example
%            f(x) = exp(-x) - x  =  0     
%
%   The goal here is to find a real value of x which satisfies f(x) = 0 using
%   the Bisection Method and Secand Method as an illustration of a typical 
%   Bracketing Mathod and Open Method, respectively
%
%   The function evaluations are done in function file RROOTS_1.M
%
%   The bisecion method is implemented in BISECTION.M and the secant method
%   is implemented in file SECANT.M.  Matlab's built-in fzero function is also
%   used.
%
%   File prepared by J. R. White, UMass-Lowell  (last update:  Nov. 2017)
%

      clear all,   close all
%
%   find root using the bisection method 
      [xr,k] = bisection(@rroots_1,0,1,1e-6,30,1);
      fprintf('\n  Zero of f(x) = exp(-x) - x  occurs at x = %12.7f \n',xr);
      fprintf('  The value of f(x) at this point is =      %12.7f \n',rroots_1(xr));
      fprintf('  The number of function evaluations needed was = %6i \n',k+2);
%
%   find root using the secant method 
      [xr,k] = secant(@rroots_1,0,1,1e-6,20,1);
      fprintf('\n  Zero of f(x) = exp(-x) - x  occurs at x = %12.7f \n',xr);
      fprintf('  The value of f(x) at this point is =      %12.7f \n',rroots_1(xr));
      fprintf('  The number of function evaluations needed was = %6i \n\n',k+2);
%
%   find root using Matlab's built-in fzero function 
      xg = [0 1];                                        % set brackets
      options = optimset('Display','iter','TolX',1e-6);  % sets display and tolerance
      xr = fzero(@rroots_1,xg,options);
      fprintf('\n  Zero of f(x) = exp(-x) - x  occurs at x = %12.7f \n',xr);
      fprintf('  The value of f(x) at this point is =      %12.7f \n',rroots_1(xr));
%
%   find root using Matlab's built-in fzero function (no edit this time)
      xg = [0 1];                                        % set brackets
      options = optimset('Display','off','TolX',1e-6);   % sets display and tolerance
      xr = fzero(@rroots_1,xg,options);
      fprintf('\n  Zero of f(x) = exp(-x) - x  occurs at x = %12.7f \n',xr);
      fprintf('  The value of f(x) at this point is =      %12.7f \n',rroots_1(xr));
%
%   find root using Matlab's built-in fzero function (last time with all defaults)
      clear all
      xg = [0 1];                                        % set brackets
      xr = fzero(@rroots_1,xg);
      fprintf('\n  Zero of f(x) = exp(-x) - x  occurs at x = %12.7f \n',xr);
      fprintf('  The value of f(x) at this point is =      %12.7f \n',rroots_1(xr));
%
%  end of problem