In: Advanced Math
f(x)=x^3-3x-1=0
x=[0,2]
epsilon=5*10^-2
1. perform the bisection method for the root in [0,2] until your root is closer to the real root within epsilon.
Let x_0=1.0, x_1=1.2
2. perform the secant method until your root is closer to the real root within epsilon.
3. do as in 2. with the Newton's method, with x_0=1.1
%%Matlab code for finding root using Newton, Secant and
Bisection method
clear all
close all
%Function for which root have to find
fun=@(x) x^3-3*x-1;
%displaying the function
fprintf('\tFor the function\n')
disp(fun)
%Root using Bisection method
x0=1; x1=2; %Initial guess
maxit=1000; %maximum iteration
[root]=bisection_method(fun,x0,x1,maxit);
fprintf('Root using Bisection method for initial guess[%f,%f] is
%2.15f.\n\n',x0,x1,root);
%Root using Secant method
x0=1; x1=2; %Initial guess
maxit=1000; %maximum iteration
[root]=secant_method(fun,x0,x1,maxit);
fprintf('Root using Secant method for initial guess[%f,%f] is
%2.15f.\n\n',x0,x1,root);
%Root using Newton method
x0=1.1; %Initial guess
maxit=1000; %maximum iteration
[root]=newton_method(fun,x0,maxit);
fprintf('Root using Newton method for initial guess %f is
%2.15f.\n\n',x0,root);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Matlab function for Bisection Method
function [root]=bisection_method(fun,x0,x1,maxit)
if fun(x0)<=0
t=x0;
x0=x1;
x1=t;
end
fprintf('\nRoot using Bisection method\n')
%f(x1) should be positive
%f(x0) should be negative
k=10; count=0;
while k>5*10^-2
count=count+1;
xx(count)=(x0+x1)/2;
mm=double(fun(xx(count)));
if mm>=0
x0=xx(count);
else
x1=xx(count);
end
err(count)=abs(fun(x1));
k=abs(fun(x1));
if count>=maxit
break
end
fprintf('\tAfter %d iteration root using
Bisection method is %f\n',count,xx(count))
end
root=xx(end);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Matlab function for Newton Method
function [root]=newton_method(fun,x0,maxit)
syms x
g1(x) =diff(fun,x); %1st Derivative of this
function
xx=x0;
%initial guess]
fprintf('\nRoot using Newton method\n')
%Loop for all intial guesses
n=5*10^-2; %error limit for close
itteration
for i=1:maxit
x2=double(xx-(fun(xx)./g1(xx))); %Newton Raphson Formula
cc=abs(fun(x2));
%Error
err(i)=cc;
xx=x2;
if cc<=n
break
end
fprintf('\tAfter %d
iteration root using Newton method is %f\n',i,xx)
end
root=xx;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Matlab function for Secant Method
function [root]=secant_method(fun,x0,x1,maxit)
%f(x1) should be positive
%f(x0) should be negative
k=10; count=0;
fprintf('\nRoot using Secant method\n')
while k>5*10^-2
count=count+1;
xx=double(x1-(fun(x1)*((x1-x0)/(fun(x1)-fun(x0)))));
x0=x1;
x1=xx;
k=abs(fun(xx));
if count>=maxit
break
end
fprintf('\tAfter %d iteration root using Secant
method is %f\n',count,xx)
end
root=xx;
end
%%%%%%%%%%%%%%%%% End of Code %%%%%%%%%%%%%%%%