Newton-Raphson Algorithm on MATLAB

Viewed 41

I am trying to create a Newton-Raphson Method script in Matlab. So far, I have this code:

%% Section 5

%----------PART A ----------
clc
clear

%Equation has P in it. e = 0.25, a
%is 2 DU. P = a(1-e^2). Thus, P = 1.875.


%f = @(x)( (1.875*sin(x))/(1+0.25*cos(x)) - 6378.14); 
f = @(x)((1.875*sin(x))/(1+0.25*cos(x)) );
%derivative of said function
df = @(x) ( ((cos(x))/(1 + 0.25*cos(x))) ) - (( sin(x)*(-0.25*sin(x)) ) / (1+0.25*cos(x))^2);

% initial guess, in radians. is theta in the original equation. Don't mess
% with this.
x = pi;
%error tolerance. Ask [REDACTED] what this should be.
tolerance = 10^-10;

%iterations are set within the for loop below. This should give us three
%iterations.

for i = 1:3
%getting the new value for x
    numerator = f(x)
    denominator = df(x)
%i'm making the numerator adn denominator separate variables so I can
%troubleshoot more easily.
    x_plusone = x - numerator/denominator
    
    %make the error into its own variable for ease of troubleshooting.  
    err = abs(x_plusone - x);
    %criteria for breaking the loop/satisfying the conditions
    if err > tolerance

        x = x_plusone;
    % updates the condition given that the criteria has not been met
    else  
    %if criteria is met, break out of the if-else loop.
        break
    end
    %something is wrong here. Maybe it's the way the loop is constructed.
end

fprintf("Your value is %x at iteration %i.",x,i)

my final x value is supposed to be 2.717. However, the algorithm doesn't seem to be going past the first guess of x = pi. It should be going through all three iterations, converging to 2.717. What is wrong with the script? did I forget to close a loop? is it the error? or is it something else? Thank you very much in advance.

0 Answers
Related