How to write Newton method with exact number of iterations and see all digit ? for example if method is required to take exact 5 iterations of newton's method

조회 수: 2 (최근 30일)
Here is my code so far, I haven't set up the N yet
function c = newton(x0, delta)
format long e
x0 = 5;
delta = 10^-8;
c = x0;
fc = f(x0);
fprintf('initial guess: c=%d, fc=%d\n',c,fc)
if abs(fc) <= delta
return;
end;
while abs(fc) > delta,
fpc = fprime(c);
if fpc==0,
error('fprime is 0')
end;
c = c - fc/fpc;
fc = f(c);
fprintf(' c=%d, fc=%d\n',c,fc)
end;
function fx = f(x)
fx = sinx;
return;
function fprimex = fprime(x)
fprimex = cosx;
return

답변 (1개)

Mischa Kim
Mischa Kim 2021년 1월 10일
편집: Mischa Kim 2021년 1월 10일
Add a loop index, e.g. ii. Also, you set your code as a function. This means you can call it, e.g., from the command window using
c = newton(1, 1e-3)
and thus it does not make sense to define x0 and delta in the function.
function c = newton(x0, delta)
format long e
% x0 = 5;
% delta = 10^-8;
c = x0;
fc = f(x0);
fprintf('Initial guess: c = %d, fc = %d\n',c,fc)
if abs(fc) <= delta
return;
end
ii = 0;
while abs(fc) > delta
ii = ii + 1;
fpc = fprime(c);
if (fpc==0)
error('fprime is 0')
end
c = c - fc/fpc;
fc = f(c);
fprintf('ii = %d: c = %10.7e, fc = %10.7e\n',ii,c,fc)
end
end
function fx = f(x)
fx = sin(x);
end
function fprimex = fprime(x)
fprimex = cos(x);
end
  댓글 수: 2
Malcolm Kevin
Malcolm Kevin 2021년 1월 10일
yes you're right. The question does not give tolerence "delta" value, but has the initial guess x0. My question is how to print out exact 5 iterations. I was just stuck in here not knowing how to set up this loop with certain variable like Maxiteration < 6 ?
Mischa Kim
Mischa Kim 2021년 1월 10일
편집: Mischa Kim 2021년 1월 10일
Well, with Newton's method you do not know the number of iteration steps. It typically depends on the tolerance, the delta you set. The smaller the delta the more iteration steps it will take to find the solution. Of course, provided that the initial guess is close enough to the solution and that the algorithm converges.
If you just want to do a certain number of iterations and then quit the algorithm you can add a condition like
while (abs(fc) > delta) && (ii < 6)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by