Newton's Method missing value

11 ビュー (過去 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 Center および File ExchangeApp Building についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by