% NEWTONDEMO Script demonstrates use of Newton's method % to solve x^3 - 2*x - 5 = 0. % x = 2; % Initial guess for root xtol = 1e-14; % Tolerance for change in x ftol = 1e-14; % Tolerance for residual itmx = 10; % Max # of iterations allowed % Print a table header disp('Iter Approximate Root x | fx | | dx |') fx = 1 + ftol; % Enforce 1 iteration dx = 1 + xtol; it = 0; while ( abs(dx) >= xtol & abs(fx) >= ftol & it < itmx ) fx = x^3 - 2*x -5; % Residual df = 3*x^2 - 2; % Derivative dx = fx/df; % Newton correction x = x - dx; % New approximate root it = it + 1; % Bump counter disp(sprintf(' %2d %21.17f %8.2e %8.2e',it,x,abs(fx),abs(dx))) end disp(sprintf('The computed root is %21.17f',x))