# Thread: new NR error problem

1. ## new NR error problem

Code:
function root =nlenewton(f,df,x0,tol,N)
%Filename: nlenewton.m
%Usage: root=nlenewton(f,df,x0,tol,N)
%(c)H
%Input
% f       function f(x) whose root is desired
% df      derivative of f(x), df=d(f(x))/dx
% x0      initial approximation
% tol     tolerence for convergence criterion
% N       maximum number of iteration
%Output
% root    approximations to the root of f(x)=0

x0=0;
tol=0.0005;
N=10;
f= 786.272-104.488*x+4.48*x^2-0.064*x^3;
df= -104.488+8.96*x-0.192*x^2;

disp('    i, x(i), f(x(i)), |x(i)-x(i-1)|');
disp('    --------------------------------');

for i=1:N
if df(x0)==0
error('Division by zero');
end
x=x0-f(x0)/df(x0);
disp([i,x,f(x),abs(x-x0);
if (abs(x-x0),tol)||(abs(f(x)),tol)
root=x;
break;
end;
if i==N
error('Method not converge after N=%d iterations.',N);
end
x0=x;
end

but i got error that
??? Error: File: nlenewton.m Line: 29 Column: 9
Illegal use of reserved keyword "if".

by the way thnx for helping me figure out what the problem before

2. Originally Posted by dlugia
Code:
function root =nlenewton(f,df,x0,tol,N)
%Filename: nlenewton.m
%Usage: root=nlenewton(f,df,x0,tol,N)
%(c)H
%Input
% f       function f(x) whose root is desired
% df      derivative of f(x), df=d(f(x))/dx
% x0      initial approximation
% tol     tolerence for convergence criterion
% N       maximum number of iteration
%Output
% root    approximations to the root of f(x)=0

x0=0;
tol=0.0005;
N=10;
f= 786.272-104.488*x+4.48*x^2-0.064*x^3;
df= -104.488+8.96*x-0.192*x^2;

disp('    i, x(i), f(x(i)), |x(i)-x(i-1)|');
disp('    --------------------------------');

for i=1:N
if df(x0)==0
error('Division by zero');
end
x=x0-f(x0)/df(x0);
disp([i,x,f(x),abs(x-x0);
if (abs(x-x0),tol)||(abs(f(x)),tol)
root=x;
break;
end;
if i==N
error('Method not converge after N=%d iterations.',N);
end
x0=x;
end

but i got error that
??? Error: File: nlenewton.m Line: 29 Column: 9
Illegal use of reserved keyword "if".

by the way thnx for helping me figure out what the problem before
If the line in question is:

Code:
        if (abs(x-x0),tol)||(abs(f(x)),tol)
what do you think this line means?

Code:
        if (abs(x-x0)<tol)||(abs(f(x))<tol)
might be better

CB