Try using the same code on f(x) = x 2 starting with x L = 1 and x R = 2. What is
ID: 3111888 • Letter: T
Question
Try using the same code on f(x) = x2 starting with xL = 1 and xR = 2. What is the
problem? Can you make your code reliable? Please think carefully about what “reliable” means
in this context. Turn in the new code with its output for this problem, as well as a hand-written
discussion of the problem you noticed and the reason behind the changes you made.
Hint: For lack of a better word, please note that a reliable code is not necessarily a code that will
return a root at any cost. If you decide that you do need to modify the code, think carefully about
how you need to change it. Consider the experience you have with other computer programs you
may use regularly.
Please use conditions below:
Write a script file that finds the smallest positive root of
f(x) = sin 3x - 2 cos x:
Use the stopping criterion |f(x*)| < 10-5. Set the maximum number of iterations to 20 and start
with xL = 0 and xR = 2.5.
Turn in the code together with an output/ printout of the results that should include at the
minimum:
- the root x*
- the value f(x*)
- the number of iterations performed
- whether convergence was reached or the maximum number of iterations reached before convergence
was achieved.
Explanation / Answer
clc;
clear all;
close all;
format long
err=10^(-5); %%% tolerence
N=20; %%% max iteration
% % % using newton raphson method
fx=@(x) sin(3*x)-cos(x);
f_x=@(x) 3*cos(3*x)+sin(x);
a(1)=0;
for n=1:N
a(n+1)=a(n)-feval(fx,a(n))/feval(f_x,a(n))
k=abs(feval(fx,a(n+1)));
if (k<10^(-5))
break;
end
end
fprintf('the root x*=%f ',a(n+1));
fprintf(' value of f(x*)=%f ', k);
fprintf('The number of iteration perform = %d ', n);
if (n==20)
fprintf('Maximum number of iteration reached first ');
else
fprintf('convergence reached first ');
end
output:the root x*=0.392699
value of f(x*)=0.000000
The number of iteration perform = 4
convergence reached first