function Newton1(x,nmax,ep,de) % Cheney/Kincaid 5th Ed., Page 106. % Newton's Method with a maximum number of iterations and % a fixed value for epsilon and delta. % x = initial guess x_0 % nmax = max iterations % ep = max error for convergence of d % de = max error for convergence of fprime % I used: % Newton1(4,100,1e-10,1e-10) tic % We will use the example on p. 107. % f(x) is really x^3 - 2*x^2 + x - 3, but the authors remind us % that the NESTED form will increase efficiency. Thus, we have % f(x) = ((x - 2)*x + 1)*x - 3 and % f'(x) = (3*x - 4)*x + 1. % Our initial value of x will be 4. % nmax = maximum number of iterations. f = @(x) ((x - 2)*x + 1)*x -3; fprime = @(x) (3*x - 4)*x + 1; % Initialize f(x_0). fx = f(x); % I guess we can start a table. % I counted out all of the field spaces. fprintf(' n x_n f(x_n)\n'); fprintf(' 0 %20.17f %20.17f\n',x,fx); % We will run nmax iterations (or fewer). for i=1:nmax % Calculate f'(x). fp = fprime(x); % If f'(x) is small enough, then stop the algorithm. if abs(fp) < de fprintf('Near root; fprime < delta\n'); toc return; end % Calculate the new value of x for this iteration. d = fx/fp; x = x - d; fx = f(x); fprintf('%3d %20.17f %20.17f\n',i,x,fx); % if abs(d) < ep fprintf('Convergence; abs(d) < epsilon\n'); toc return; end end % We've run out of iterations! fprintf('Did not converge!\n'); toc