Newton's Method missing value

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.

回答(1 个)

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

类别

帮助中心File Exchange 中查找有关 App Building 的更多信息

产品

标签

Community Treasure Hunt

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

Start Hunting!

Translated by