In: Advanced Math
why can't we use bisection methods or newton's method for nonconvex functions? x^4+x^3-2x^2-2x especially for this function?
%%Matlab code for finding root using newton secant bisection and
false
clear all
close all
%function for which root have to find
fun=@(x) x.^4+x.^3-2.*x.^2-2.*x;
fprintf('For the function f(x)=')
disp(fun)
a=1;b=2;
xx=linspace(1,2);
yy=fun(xx);
plot(xx,yy)
xlabel('x')
ylabel('f(x)')
title('x vs. f(x) plot')
[root]=bisection_method(fun,a,b,1000);
fprintf('\tRoot using Bisection method is %f.\n',root)
[root]=newton_method(fun,a,1000);
fprintf('\tRoot using Newton method is %f.\n',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^-10
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
fprintf('\tAfter %d iteration root using Bisection method is
%f\n',count,xx(count))
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^-15; %error limit for close
itteration
for i=1:maxit
x2=double(xx-(fun(xx)./g1(xx))); %Newton Raphson Formula
cc=abs(double(fun(x2)));
%Error
err(i)=cc;
xx=x2;
if cc<=n
break
end
end
fprintf('\tAfter %d iteration root using Newton
method is %f\n',i,xx)
root=xx;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%