format compact 
format short
clc % clear screen

display('** f is exp(x)-4x')
f = @(x) exp(x)-4*x;
intervalLow = 0;
intervalHigh = 1;
zeta = 1e-7;
root = binarySearch( f, intervalLow, intervalHigh, zeta);
display(['binarySearch gives root at approx ', num2str(root) ])

% explore the program by "uncommenting"...

% root = binarySearchV2( f, intervalLow, intervalHigh, zeta);
% display(['binarySearchV2 gives root at approx ', num2str(root) ])
% 
% 
% % let's test the case where there is no root in the initial interval
% display('** initial interval is [1,2]')
% intervalLow = 1;
% intervalHigh = 2;
% % 
% % Note that binarySearch does not test whether there is a root
% %   it gives a bad answer: it is an *unreliable* function
% root = binarySearch( f, intervalLow, intervalHigh, zeta);
% display(['binarySearch gives root at approx ', num2str(root) ])
% 
% % binarySearchV2 includes the initial check
% root = binarySearchV2( f, intervalLow, intervalHigh, zeta);
% display(['binarySearchV2 gives root at approx ', num2str(root) ])
% 
% 
% let's try it for a more complicated function that involves large matrices
% n=4000
% % nxn matrix with random numbers
% M=rand(n,n);
% % make a symmetric matrix (for real matrices, M' is the transpose of M)
% M = M + M';
% 
% display('top left block of matrix M')
% display( M( 1:5 , 1:5 ) )
% 
% % This function computes a matrix with elements
% %   A_ij = exp( x M_ij )
% % computes the largest eigenvalue lambda of A 
% % and returns lambda - 2*n
% display('** ff is related to the largest eVal of an nxn matrix')
% ff = @(x) eigs( exp(x*M), 1 )  - 2*n;
% 
% display(['** x is 0, ff(x) is ', num2str(ff(0)) ])
% display(['** x is 1, ff(x) is ', num2str(ff(1)) ])
% % note exp(M) for a matrix takes the exponential of each element
% % 
% % we expect an eigenvalue in this range 
% intervalLow = 0; intervalHigh = 5;

% tic
% root = binarySearchV2( ff, intervalLow, intervalHigh, zeta);
% timeTaken = toc;
% display(['binarySearchV2 gives root at approx ', num2str(root), ...
%            ' in ' , num2str(timeTaken) , 'seconds'])
% 
% 
% tic
% root = binarySearch( ff, intervalLow, intervalHigh, zeta);
% timeTaken = toc;
% display(['binarySearch gives root at approx ', num2str(root), ...
%            ' in ' , num2str(timeTaken) , 'seconds'])
%    
% % do this with the matlab built-in solver
% % set the tolerance to zeta for a fair comparison
% fzOptions = optimset('TolX', zeta);
% tic
% root = fzero( ff, 1 , fzOptions );
% timeTaken = toc;
% display(['built-in fzero gives root at approx ', num2str(root), ...
%            ' in ' , num2str(timeTaken) , 'seconds'])
