Newton's Method missing value

11 views (last 30 days)
Isaac Soria
Isaac Soria on 9 Sep 2022
Edited: Torsten on 9 Sep 2022
I wrote Newton's method to be
function [cVec,n] = Newtons_method(f,fp,x0,tol,nmax)
cVec = [];
cVec(1)=x0;
i=0;
while i <=nmax
i=i+1;
cVec(i)=x0;
c = x0-(f(x0)/fp(x0));
if abs(c-x0)<tol
c=x0;
break;
else
x0=c;
end
end
n=i-1;
cVec=cVec';
end
and used the following to call it
f=@(x)(x.^2-3);
fp=@(x)(2.*x);
x0=2;
tol=10^-10;
nmax= 100;
[c,n]=Newtons_method(f,fp,x0,tol,nmax)
From this, I get a [5,1] column vector but I'm supposed to get a [6,1] vector. I've messed around with the placement of certain lines of code and indices, but haven't gotten the desired result.
Thanks in advance.

Answers (1)

Torsten
Torsten on 9 Sep 2022
Edited: Torsten on 9 Sep 2022
If n is the number of Newton steps, you must start with n = 0 instead of n = 1 in "Newtons_method".
I counted the number of Newton steps + the initial value, thus the length of the array cVec.
f = @(x) x.^2-3;
fp = @(x) 2.*x;
x0 = 2;
tol = 10^-10;
nmax = 100;
format long
[c,n] = Newtons_method(f,fp,x0,tol,nmax)
c = 6×1
2.000000000000000 1.750000000000000 1.732142857142857 1.732050810014728 1.732050807568877 1.732050807568877
n =
6
function [cVec,n] = Newtons_method(f,fp,x0,tol,nmax)
cVec(1) = x0;
n = 1;
while n <= nmax
c = x0 - f(x0)/fp(x0);
n = n+1;
cVec = [cVec;c];
if abs(c-x0) < tol
break;
else
x0 = c;
end
end
end

Categories

Find more on App Building in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!