% Unit 3 (MATLAB Course @ UAM)
% (c) Alexander Knebe

%========================================================
% root of x^2
%========================================================
clear all
close all
clc
format long

% start with simply plotting x^2
x   = linspace(-2,1,1000);
f   = @(x)(x.^2);  %%% it will NOT work...
%f   = @(x)(x.^3);  %%% for this function it will work as it changes sign when passing through the root

plot(x,f(x),x,0), xlabel('r'), ylabel('f')

%-----------------------------
% root finding via bi-section
%-----------------------------
% initial guess for the root
a = -1.50; % you can only find the root when the interval is symmetric [-a,+a]
b = +2.0;
n = 0;    % we also count the number of iterations

while abs(b-a)>1e-8
    
   x0 = (a+b)/2;
   n  = n + 1;
   
   
   if f(a)*f(x0) > 0
       a = x0;
   else
       b = x0;
   end
   
end

x0 = (a+b)/2   % print the root
n              % print the number of iteration

[x0, n] = bisec(f, -1.5, 2.0);

% mark root
hold on
plot([x0],[0],'sr')
