I can't get this IF statement to work

조회 수: 1 (최근 30일)
Sarfraz Khan
Sarfraz Khan 2020년 3월 3일
댓글: Rena Berman 2020년 5월 14일
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:
If I hadnt included the 1:100 statement the code would run on forever. Please help!!
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
  댓글 수: 2
Rik
Rik 2020년 3월 3일
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
Rena Berman 2020년 5월 14일
(Answers Dev) Restored edit

댓글을 달려면 로그인하십시오.

채택된 답변

David Hill
David Hill 2020년 3월 3일
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:
  댓글 수: 2
Sarfraz Khan
Sarfraz Khan 2020년 3월 3일
Thanks so much for your previous answer.
How would I use a while loop here? I have attempted but getting similar issues :(
David Hill
David Hill 2020년 3월 3일
root=x-f(x)/fp(x);
while abs(root-x)>tol
x=root;
root=x-f(x)/fp(x);
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by