%% example using the bisection.m external function routine
% 
clear all
close all
clc
format long

fun=@(x)(-3*x.^2+x.^4+x.^5/10);

a=1; b=2; err=eps;
[x01, fx01, iter1] = bisection(fun, a, b, err)

a=-3; b=01; err=eps;
[x02, fx02, iter2] = bisection(fun, a, b, err)

% plot the function to see whether we have started from the correct
% intervals for the search of the zeros

N=100;
x=linspace(-2.2,2,N);
figure(1)
hold on
plot(x,fun(x),'-b','Linewidth',2)
plot(x,zeros(N,1),'k--')
plot(x01,fx01,'rs','Linewidth',2)
plot(x02,fx02,'rs','Linewidth',2)
xlabel('x')
ylabel('f(x)')
hold off

%% example using the NewtonRaphson.m external function routine
% 
clear all
close all
clc
format long

fun=@(x)(-3*x.^2+x.^4+x.^5/10);
funp=@(x)(-6*x+4*x.^3+x.^4/2);

x0=2; err=eps;
[xzero1, fzero1, iter1] = NewtonRaphson( fun, funp, x0, err )

x0=-3;
[xzero2, fzero2, iter2] = NewtonRaphson( fun, funp, x0, err )

% plot the function to see whether we have started from meaningfull
% initial conditions and to plot the zeros we found

N=100;
x=linspace(-2.2,2,N);
figure(1)
hold on
plot(x,fun(x),'-b','Linewidth',2)
plot(x,zeros(N,1),'k--')
plot(xzero1,fzero1,'rs','Linewidth',2)
plot(xzero2,fzero2,'rs','Linewidth',2)
xlabel('x')
ylabel('f(x)')
hold off

%% same example using the NewtonRaphson_no-analytic.m 
% external function routine
% 

x0=2; err=eps; dx=10^(-5);
[xzero1, fzero1, iter1] = NewtonRaphson_noanalytic(fun, x0, dx, err)

x0=-3;
[xzero2, fzero2, iter2] = NewtonRaphson_noanalytic(fun, x0, dx, err)

% plot
figure(2)
hold on
plot(x,fun(x),'-b','Linewidth',2)
plot(x,zeros(N,1),'k--')
plot(xzero1,fzero1,'rs','Linewidth',2)
plot(xzero2,fzero2,'rs','Linewidth',2)
xlabel('x')
ylabel('f(x)')
hold off