-1
function [ sol, flag ] = newtonx(sx, relerr, maxit, func)
% [SOL,FLAG]=NEWTONX(SX, RELERR, MAXIT, FUNC)
%
% Solves f(x)=0 using Newton’s method
%
% Input: scalar sx - starting point of the iteration
%        small positive scalar relerr - desired relative error
%        positive integer maxit - maximum no. of iterations permitted
%        func: name of the program that defines f(x);
%
%        Note: when running newtonx on the problem defined by func, you
%        must enter @func (func with symbol @ attached) in the input line.
%        The calling sequence for the program func must have the format
%               [yval, yder]=func(x)
%        where x is the point used to compute yval=f(x) and yder=f’(x).
%
% Output: scalar sol - solution found
%        scalar flag - flag=0 indicates solution successfully found
%                     flag=1 indicates derivative too small; halt
%                     flag=2 indicates too many iterations; halt
k=0 ;
while (k<maxit)
    k=k+1 ;
    [yval, yder]=func(sx) ; % evaluate f(x) and f’(x)
    if (abs(yder)<abs(yval)*sqrt(eps))
        sol=[]; flag=1 ; return % derivative too small
    end
    sx = sx - yval / yder ; % take the Newton step
    if (relerr == 0)
        sol=sx ; flag=0 ; return % succesful termination
    end
end
sol=[]; flag=2 ; % failure: too many steps
end

I need help coming up with suitable termination criteria, for now, I have (relerr==0) but I am sure that is incorrect. Any help or hints would be awesome, I'm not sure what to even do.

sam
  • 1
  • 1
  • 6
  • I would assume it has something to do with the relerr since it is not used anywhere in the function – sam Aug 11 '20 at 03:45
  • welcome to stackoverflow. Please post code rather than screenshots. This gives others the option to reproduce your problem. With regards to your stopping criteria, you can pick a maximum number of steps, time, a minimum change in the cost or in the derivative... there are plenty of options, so you may want to be a bit more precise. – max Aug 11 '20 at 05:30

1 Answers1

0

|sx-sx_{prev}| = |yval/yder|

so the relative error formula is |yval/(sx * yder)| or in matlab terminialogy it is abs(yval/(sx * yder))

abs(yval/(sx * yder)) < relerr

sam
  • 1
  • 1
  • 6