Fundamentals of Numerical Mathematics for Physicists and Engineers. Alvaro Meseguer
Чтение книги онлайн.
Читать онлайн книгу Fundamentals of Numerical Mathematics for Physicists and Engineers - Alvaro Meseguer страница 14
% Code 2: Newton's method for solving f(x) = 0 % Input: 1. a: initial guess % 2. tol: tolerance so that abs(x_k+1 - x_k) < tol % 3. itmax: maximum number of iterations allowed % 4. fun: function's name % 5. dfun: derivative's name % (If dfun = ‘0’, then f'(x) is approximated) % Output: 1. xk: resulting sequence % 2. res: resulting residuals % 3. it: number of required iterations function [xk,res,it] = newton(a,tol,itmax,fun,dfun) xk = [a]; fk = feval(fun,xk); res = abs(fk); it = 0; tolk = res(1); dx = 1e-8 ; while it < itmax & tolk > tol if dfun == ‘0’ dfk = (feval(fun,xk(end)+dx)-fk)/dx; else dfk = feval(dfun,xk(end)); end xk = [xk, xk(end) - fk/dfk]; fk = feval(fun,xk(end)); res = [res abs(fk)]; tolk = abs(xk(end)-xk(end-1)); it = it + 1; end
Let us compare the performance of Newton's method with the bisection by applying both algorithms to solve the cubic equation (1.2) starting from the same initial guess
Table 1.1 Iterates resulting from using bisection
and Newton–Raphson when solving (1.2), with added shading of converged digits.
|
Bisection |
Newton–Raphson |
|
|
0 | 1.5 | 1.5 |
|
|
1 | 1.75 | 1.869 565 215 355 94 |
|
|
2 | 1.875 | 1.799 452 405 786 30 |
|
|
3 | 1.812 5 | 1.796 327 970 874 37 |
|
|
4 | 1.781 25 | 1.796 321 903 282 30 |
|
|
5 | 1.796 875 | 1.796 321 903 259 44 |
|
|
6 | 1.789 062 5 | 1.796 321 903 259 44 |
|
|
7 | 1.792 968 75 |
|
||
8 | 1.794 921 875 |
|
||
|
|
|