Write two codes Newton Method and Bisection Method to find the roots. (a) Using
ID: 2264839 • Letter: W
Question
Write two codes Newton Method and Bisection Method to find the roots. (a) Using bisection method: on the interval xL = 0, xR = pi . Do you encounter any problems?
Is there a way the code can be improved (again, in the sense of making it more `reliable' as
in the first homework)? Explain any changes you make to your code.
(b) Using Newton's method: with the following initial guesses:
x0 = pi/2
x0 = 5pi
x0 = 10pi
Use an accuracy of a = 10-5, and a maximum number of 20000 iterations. Explain the
different behavior for the three starting values?
For each part, submit the equivalent files: a function file, script file, and
output file. Your output must also meet the same requirements: the value of the root, function
value at the root, and number of iterations performed.
Explanation / Answer
a) %%% Bisection method
at both point x=0 and x=pi f(x) is positive
Thus there need to change a initial point
lets Xr=pi/2
%%% Matlab code
clc;
clear all;
close all;
format long
format compact
syms x
f=1/2+x^2/4-x*sin(x)-cos(2*x)/4;
tol=0.00001;
% % % bisection method
disp('Bisection method :');
a=pi/2;
b=0;
for n=1:100
l1=subs(f,a);
l2=subs(f,b);
c(n)=(a+b)/2;
l3=subs(f,c(n));
if (n>2)
if (abs( c(n)-c(n-1))< tol)
break;
end
end
if ( l3 < 0 )
a=c(n);
else
b=c(n);
end
end
fprintf('roots of eqution is : %f ', c(end) );
OUTPUT:
Bisection method :
roots of eqution is : 1.029271
b) Newton raphson method
syms x
f=1/2+x^2/4-x*sin(x)-cos(2*x)/4;
tol=0.00001;
x0=[pi/2 5*pi 10*pi];
% % % % N-R Method
% disp('Newton Raphson method');
fprintf('Initial guess Root value at root Number of iteration ');
for k=1:length(x0)
s(1)=x0(k);
for n=1:2000
l1=subs(f,s(n));
l2=subs(diff(f),s(n));
s(n+1)=s(n)-l1/l2;
e=abs(s(n+1)-s(n));
if (e < tol)
break;
end
end
v=subs(f,s(n+1));
fprintf(' %f %f %1.8f %d ',x0(k),s(n+1),v,n);
end
OUTPUT:
Initial guess Root value at root Number of iteration
1.570796 1.029276 0.00000000 5
15.707963 2.192591 0.00000000 33
31.415927 -1.029276 0.00000000 87
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.