find the error in this newton-raphson convergence: in matlab

To find the error in the convergence of the Newton-Raphson method in MATLAB, you can compute the absolute value of the difference between the current estimate and the previous estimate.

Here is an example code to illustrate how to find the error in the Newton-Raphson convergence:

main.m
% Function to find the root using Newton-Raphson method
function root = newtonRaphson(func, derivative, initial_guess, max_iter, tolerance)
    root = initial_guess;   % Initial guess for the root
    old_root = inf;         % Variable to hold the previous estimate
    iter = 0;               % Iteration counter

    % Iterate until convergence or maximum iteration limit is reached
    while abs(root - old_root) > tolerance && iter <= max_iter
        old_root = root;                           % Update the previous estimate

        % Compute the new estimate for the root using Newton-Raphson formula
        root = root - func(root) / derivative(root);

        iter = iter + 1;                            % Increment the iteration counter
    end

    % Check if the method converged or reached the maximum iteration limit
    if iter > max_iter
        disp("Newton-Raphson method did not converge within the maximum number of iterations.");
    else
        disp("Root found successfully using Newton-Raphson method.");
    end
end

% Example usage
f = @(x) x^3 - x - 1;                           % Function
df = @(x) 3 * x^2 - 1;                          % Derivative of the function
initial_guess = 1;                              % Initial guess for the root
max_iterations = 100;                           % Maximum number of iterations
tolerance = 1e-6;                               % Tolerance for convergence

root = newtonRaphson(f, df, initial_guess, max_iterations, tolerance);
error = abs(root - initial_guess);
disp("Error in convergence: " + error);
1575 chars
35 lines

In this example, the newtonRaphson function takes in the function func, its derivative derivative, the initial guess for the root initial_guess, the maximum number of iterations max_iter, and the tolerance for convergence tolerance.

Within the while loop, the previous estimate old_root is updated, and the new estimate for the root is computed using the Newton-Raphson formula. The loop continues until the difference between the current estimate and the previous estimate is less than the specified tolerance or the maximum number of iterations is reached.

After finding the root, the error in convergence is calculated as the absolute difference between the root and the initial guess. This error is stored in the error variable and displayed as the output.

Please note that this code assumes that the Newton-Raphson method converges within the maximum number of iterations. If the method does not converge, you may need to adjust the initial guess or increase the maximum number of iterations to avoid premature termination.

gistlibby LogSnag