Newton's Method missing value

조회 수: 10 (최근 30일)
Isaac Soria
Isaac Soria 2022년 9월 9일
편집: Torsten 2022년 9월 9일
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개)

Torsten
Torsten 2022년 9월 9일
편집: Torsten 2022년 9월 9일
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

카테고리

Help CenterFile Exchange에서 App Building에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by