Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write your own MATLAB code (as simple as possible) to implement the Newton-Raphs

ID: 1719278 • Letter: W

Question

Write your own MATLAB code (as simple as possible) to implement the Newton-Raphson method as a way to find all the zeros of the function f(x) = exp(-0.1x)cos(8x)x^2 on the interval [-1,1]. In order to find all the zeros you will need to use different initial (starting) positions. For each zero you identify, specify what those initial positions are. Perhaps you'll want to select regularly spaced starting points on the interval [-1,1] to make sure you don't miss any zeros. You code must display the function and the result of each iteration graphically, so that we can see the progress (evolution) of the Newton-Raphson loop. To get any credits for this problem, you are not allowed to use a for loop as we used in class. Instead, you are required to use a while loop. The reason for this requirement is that in real applications, we need to be able to allow for a flexible number of iterations to take place before we reach a solution. A for loop with a fixed number of iterations would not give us the flexibility needed to tackle many problems. For more information about while loops in MATLAB, see http://www. mathworks. com/help/matlab/ref/while.html. You will need to choose a criterion for exiting the loop when your code decides that the algorithm has finally converged to a solution (a zero of the function). What criteria should be used to decide convergence? How does the result depend on your choice of initial condition? What algorithm does the MATLAB command f zero uses by default? Compare the performance of your code against the output of the f zero command.

Explanation / Answer

The matlab script is as follows:

h=0.1;
r=[-1:h:1];
n=2/h +1;
err=0.01;
for a=1:n
a0=r(a);
x(1)=a0;
diff=1;
b=2;
while (diff>err)
f=exp(-0.1*x(b-1))*cos(8*x(b-1))*(x(b-1)^2);
df=-0.1*exp(-0.1*x(b-1))*x(b-1)*((x(b-1)-20)*cos(8*x(b-1))+80*x(b-1)*sin(8*x(b-1)));
x(b)=x(b-1)-f/df;
diff=abs((x(b)-x(b-1))/x(b-1)*100);
b=b+1;
end
root(a)=x(b-1);
end

Final roots are in root variable

The roots are as follows:

-0.981747704247707   -0.981747704370194   -0.196349540849363   -0.589048622548090   -0.589048622548886   -0.589048622548102   -0.196349540849364   -0.196349540887052   -0.196349540849661   -1.21808191414918e-162   NaN   1.21462576734430e-162   0.196349540849622   0.196349540868666   0.196349540928752   0.589048622548090   0.589048622548609   0.589048625475711   -1.53897855945975e-162   0.981747704279771   0.981747704247222

the exclusive roots are :(-0.98147,-0.58904, -0.19635, 0, 0.58904, 0.981747)