|
| 1 | +function root = newtons_method(x0, f, f_prime, tolerance, epsilon, max_iterations) |
| 2 | +% NEWTONS_METHOD Newton–Raphson root-finding algorithm |
| 3 | +% Source: Wikipedia |
| 4 | +% root = newtons_method(x0, f, f_prime, tolerance, epsilon, max_iterations) |
| 5 | +% |
| 6 | +% Inputs: |
| 7 | +% x0 - Initial guess for the root |
| 8 | +% f - Function handle whose root we want to find |
| 9 | +% f_prime - Derivative of the function (function handle) |
| 10 | +% tolerance - Stop if successive estimates differ by less than this |
| 11 | +% epsilon - Avoid division if derivative magnitude < epsilon |
| 12 | +% max_iterations - Maximum allowed number of iterations |
| 13 | +% |
| 14 | +% Output: |
| 15 | +% root - Approximate root (or NaN if not converged) |
| 16 | + |
| 17 | +root = NaN; % Default return value if not converged |
| 18 | + |
| 19 | +for k = 1:max_iterations |
| 20 | + y = f(x0); |
| 21 | + yprime = f_prime(x0); |
| 22 | + |
| 23 | + % Avoid division by very small derivative |
| 24 | + if abs(yprime) < epsilon |
| 25 | + fprintf('Derivative too small. Stopping at iteration %d.\n', k); |
| 26 | + return |
| 27 | + end |
| 28 | + |
| 29 | + % Newton update |
| 30 | + x1 = x0 - y / yprime; |
| 31 | + |
| 32 | + % Check for convergence |
| 33 | + if abs(x1 - x0) <= tolerance |
| 34 | + root = x1; |
| 35 | + fprintf('Iter %d \n x = %d .\n', k,x1); |
| 36 | + fprintf('Converged after %d iterations.\n', k); |
| 37 | + return |
| 38 | + end |
| 39 | + |
| 40 | + % Prepare for next iteration |
| 41 | + x0 = x1; |
| 42 | + |
| 43 | + % Display current step values |
| 44 | + fprintf('Iter %d \n x = %d \n', k,x0); |
| 45 | +end |
| 46 | + |
| 47 | +fprintf('Did not converge within %d iterations.\n', max_iterations); |
| 48 | + |
| 49 | +end |
0 commit comments