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

(a) Write a MATLAB function, called Newtons_method that inputs a function, f, it

ID: 3111838 • Letter: #

Question

(a) Write a MATLAB function, called Newtons_method that inputs a function, f, it's derivative f', an initial guess x_0, an error tolerance, tol, and a maximum number of iterations, N, and outputs the root of f obtained using Newton's method (denoted by c), starting with x_0. Your function should have an error defined by err = |x_n - x_n - 1|, and stop when the error is less than the tolerance, or if the number of iterations exceeds N - whichever happens first. Your function header should look something like: function [c, n, err] = Newtons_method (f, fp, x0, tol, N) where n is the last iteration when you stop. (b) Use the function you created in part (a) to find the root of the equation arctan(x) = 1 with initial guess x_0, to an accuracy of less than elementof = 10^-8. Did your method converge, and if so, how many iterations did it take? If not, why didn't it converge, and what happened-did it diverge, or end up in an infinite loop? i. x_0 = 2 ii. x_0 = -2 (c) For one of the two previous cases, plot on the same figure the function at hand, and the first 3 iterations of Newton's method in dashed lines.

Explanation / Answer

function[c,n,err]=Newtons_method(f,fp,x0,tol,N)
%x0 initial guess
%f function
% fp derivative of f
%tol tolerence
%N max iterations
%     f = inline(f);
%     fp = inline(fp);
n=0;
err=0.1;
while (abs(err>tol)& (n<=N))
   
y1=x0-(f(x0)/fp(x0));%Newton method

err=abs((y1-x0)); %erorr

% if abs(erorr<1e-3)
% break
%end
n=1+n;
x0=y1;
c(n+1)=x0;
end

clc;

clear all;

f=@(x)(atan(x)-1);
fp=@(x)1/(1+x^2);
x0=2;
tol=1e-8;
N=100;
[c,n,err]=Newtons_method(f,fp,x0,tol,N)
x=0:length(c)-1
plot(x,c)
hold on
plot(x,f(x),'r')
legend('c','f')

%% Note :both the file should save in one folder

x0=2

then

c =

         0    1.4643    1.5535    1.5574    1.5574    1.5574


n =

     5


err =

2.1656e-011

x0=-2

then

c =

1.0e+202 *

         0    0.0000   -0.0000    0.0000   -0.0000    0.0000   -0.0000    0.0000   -0.0000    5.2492      -Inf       NaN


n =

    11


err =

   NaN

x0=-2 is not convergening becuse derivative of is going to zero