Errors in Newton Raphson Code

5 views (last 30 days)
Natalie Spalding
Natalie Spalding on 22 Feb 2021
Answered: Alan Stevens on 22 Feb 2021
Given:
What am I doing wrong here? It runs forever and doesn't really give me an answer-so trying to figure out where it's open-ended.
%% Problem 2b. Newton-Raphson Method (Needs Help)
clear all
clc
i=1;
x=0.1;
while (1)
fx=log(4/3)*cos(exp(x));
fpx=-log(4/3)*(cos(exp(1)));
xnew=x-fx/fpx;
err=abs((xnew-x)/xnew);
if err<(1*10^(-8))break,end;
x=xnew;
i=i+1;
end
i
x

Answers (1)

Alan Stevens
Alan Stevens on 22 Feb 2021
Again, more like this
% f = 3*exp(x)-4*cos(x)
% df/dx = 3*exp(x)+4*sin(x)
i=1;
x=0.1;
err = 1;
while err>10^-8 && i<100
xold = x;
fx=3*exp(x)-4*cos(x);
fpx= 3*exp(x)+4*sin(x);
x=x-fx/fpx;
err=abs((x-xold)/x);
i=i+1;
end
disp(x)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!