%% Zeros and Root Finding
%% Bisection Method.
%

clear
M=2;
a=1;
b=2;
k=0;
format long
while b-a>eps
    x=(a+b)/2;
    if x^2>2
        b=x;
    else
    a=x;
    end
    k=k+1;
end
a
b
k

%
%% Hexadecimal values
%

format hex
a
b

%
% Look for where there is a sign change.
%

f=@(x) x^2-2;

a=1;
b=2;
k=0;
while abs(b-a) > eps*abs(b)
    x=(a+b)/2;
    if sign(f(x)) == sign(f(b))
        b=x;
    else a=x;
    end
    k=k+1;
end
format long
a
b
k

%
%% Newton's Method
%

fprime=@(x) 2*x;
a = 1;
b = 2;
k=0;
x = a;
xprev = b;
while abs(x-xprev) >eps*abs(x)
    xprev=x;
    x = x - f(x)/fprime(x);
    k = k + 1;
end
x
k

%
%% Fixed Point Iteration
%

f = @(x) 2*x.*(1-x);

x(1) = .1;
for k=2:10
    x(k)=f(x(k-1));
end
x

%
%% Cobweb Diagram
%

fplot(f,[0,1])
hold on
line([0,1],[0,1])
line([x(1),x(1)],[0,f(x(1))])
for k=2:10
    line([x(k-1),x(k),x(k)],[f(x(k-1)),x(k),f(x(k))]);
end
hold off

%
%% Secant Method
%

a = 1;
b = 2;
k=0;
while abs(b-a) >eps*abs(b)
    c = a;
    a = b;
    s = (f(b)-f(c))/(b-c);
    b = b - f(b)/s;
   % b = b + (b-c)/(f(c)/f(b)-1); Compact, one step
    k = k +1;
end
b
k