In: Advanced Math
MatLab code for Bisection and Newton Method to find root for f(k) = p(k)^3+2*(p(k)^2)-10 on interval [-1,2]. P(o)=1.5, P(1)=2.
Answer=
1.654249
%%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+2.*x.^2-10;
%plotting of the function
xx=linspace(-1,2,1001);
yy=fun(xx);
plot(xx,yy)
xlabel('x')
ylabel('y')
title('f(x) vs x plot')
%displaying the function
fprintf('For the function\n')
disp(fun)
%Root using Newton method
x0=2; %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',x0,root);
%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',x0,x1,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
%f(x1) should be positive
%f(x0) should be negative
k=10; count=0;
while k>eps
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
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]
%Loop for all intial guesses
n=eps; %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
end
root=xx;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%