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

3. Write a MATLAB function, called Newtons_method that inputs a function, f, it\

ID: 2259273 • Letter: 3

Question

3. Write a MATLAB function, called Newtons_method that inputs a function, f, it's derivative f', an initial guess o, 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 zo- Your function should have an error defined by err-^n - xn-il, 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 Use the function you created to find the root of the equation arctan(x)-1 with initial guess zo 2, to an accuracy of less than e 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? Plot on the same graph the function and the axis y = 0. Test with =-2. What is happening ?

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote