# I can't get this IF statement to work

5 views (last 30 days)
Sarfraz Khan on 3 Mar 2020
Commented: Rena Berman on 14 May 2020 at 16:46
Hi, I have been trying to programme newtons law of itterations, which is an itterative method which converges to the unknown point we are trying to figure out. I have got my code to do the hard part. I would however like my code to break as soon as the same figure begins to repeat itself. Please see below:
f = @(x) exp(x)-1.5+atan(x);
g = @(x) exp(x)+1/((x^2)+1);
x0 = 50
for i = 1:100
x1 = x0 - (f(x0)/g(x0)) %Newtons Formula
if x0 == x1
else
x0=x1
end
end

Rik on 3 Mar 2020
Why did you remove your question? That is extremely rude. Now nobody can benefit from your question if they have a similar issue.
Rena Berman on 14 May 2020 at 16:46

David Hill on 3 Mar 2020
f = @(x) exp(x)-1.5+atan(x);
g = @(x) exp(x)+1/((x^2)+1);
x0 = 50;
tol=1e-6;
for i = 1:100
x1 = x0 - (f(x0)/g(x0)); %Newtons Formula
if abs(x0-x1)<tol
break;
else
x0=x1;
end
end
You could also do a while loop:

Sarfraz Khan on 3 Mar 2020
How would I use a while loop here? I have attempted but getting similar issues :(
David Hill on 3 Mar 2020
root=x-f(x)/fp(x);
while abs(root-x)>tol
x=root;
root=x-f(x)/fp(x);
end