Advertisement
Guest User

Newton1

a guest
Apr 21st, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Octave 1.05 KB | None | 0 0
  1. function approximateZero = newtonsMethod( fnc, x0, tol )
  2. %  implementation of Newton's Method for finding a zero of a function
  3. %  requires a symbolic expression, a starting point, and a tolerance as input
  4. %  produces either an input, which when substituted into the given expression,
  5. %  yields an output with absolute value less than the specified tolerance,
  6. %  or a warning message indicated that the tolerance has not been met.
  7.  
  8. %  Author:  R Smyth
  9. %  Version: 1.0  8/11/2013
  10.  
  11. % Since convergence is not guaranteed for Newton's method,
  12. % set a maximum number of iterations.
  13. % Of course we could have let the user control this parameter.
  14. maxNumIter = 20;  
  15. itCounter = 0;  % Initialize iteration counter.
  16.  
  17. syms fp;   % derivative
  18. fp = diff(fnc);
  19.  
  20. xcur = x0;
  21. while ( (abs(subs(fnc,xcur))>tol)  &  (itCounter<maxNumIter) )
  22.     xcur = double(xcur - subs(fnc,xcur)/subs(fp,xcur));
  23.     itCounter = itCounter+1;
  24. end
  25.  
  26. if( abs(subs(fnc,xcur))>tol )
  27.     disp(['Warning:  Tolerance not met after ' num2str(maxNumIter) ' iterations.']);
  28. end
  29.  
  30. approximateZero = xcur;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement