How can i correct Newton rhapson method??

2 views (last 30 days)
Jo on 21 Oct 2013
Edited: VBBV on 29 Jan 2022
In Newton rhapson method ,i try to solve nonlinear equation . I think below cod is right. but values are not shown .
i don't understand why the result show just '120' as value. x f(x) 120.000000, 48.000000 x f(x) 102.000000, 120.000000 what's the error in below ???
end
f=inline('exp(-x)-x','x');
df=inline('-exp(-x)-1','x');
epsilon=0.0001;
imax=1000;
x0=input('initial xo=');
fx0=f(x0);
if abs(fx0)<=epsilon
fprintf('xo is value');
return;
end
if abs(df(x0))<=epsilon
fprintf('input another xo');
return;
end
for iter=1:imax
x0=x0-fx0/df(x0);
fx0=f(x0);
fprintf('\n x f(x) %f, %f','x0','fx0');
if abs(fx0)<=epsilon
fprintf('\n value x= %f','x0');
return;
end
end

Pourya Alinezhad on 21 Oct 2013
you may use somthing like this :
while abs(xold -xnew) > tol
xold = xnew;
xnew = xold - feval(f,xold)/feval(fprime,old);
end
out = xnew;
delete the "for" loop and use a while command instead.

Pourya Alinezhad on 21 Oct 2013
the algorithm should be like this pseudo code...
function out = Newton(f,fprime,xstart,tol)
xold = xstart;
xnew = xold - feval(f, xold)/feval(fprime,xold);
while abs(xold -xnew) > tol
xold = xnew;
xnew = xold - feval(f,xold)/feval(fprime,old);
end
out = xnew;

VBBV on 29 Jan 2022
Edited: VBBV on 29 Jan 2022
f=@(x) exp(-x)-x;% Use function handle
df=@(x) -exp(-x)-1;
epsilon=0.0001;
imax=1000;
x0= 2;
fx0=f(x0);
if abs(fx0)<=epsilon
fprintf('xo is value');
return;
end
if abs(df(x0))<=epsilon
fprintf('input another xo');
return;
end
for iter=1:imax
x0=x0-fx0/df(x0)
fx0=f(x0);
fprintf('\n x f(x) %f, %f',x0,fx0);
if abs(fx0)<=epsilon
fprintf('\n value x= %f',x0);
return;
end
end
x0 = 0.3576
x f(x) 0.357609, 0.341738
x0 = 0.5587
x f(x) 0.558708, 0.013239
x0 = 0.5671
x f(x) 0.567130, 0.000020
value x= 0.567130
You are using variable as symbol in fprintf. Check with above code