What is causing this to have an infinite loop??

2 次查看(过去 30 天)
%testing our newton's method on a known problem
%we know the root is pi
p0 = 1;%initial guess
tol = 1e-8;
exact = 3.14159;%exact root
%enter function and its derivative
f = @(x) sin(x);
fp = @(x) cos(x);
%compare initial guess to exact root
diff = abs(p0-exact);
%iterate newton's method
while diff > tol
p = p0 - f(p0)/fp(p0);
diff = abs(p-exact); %stop when our iterate is close to the exact root, pi
p0 = p;
end
%print the root to the screen
p
  2 个评论
Guillaume
Guillaume 2018-3-2
Completely unrelated to the problem: it is not a good idea to name a variable diff as it will prevent you from using the very useful diff function.

请先登录,再进行评论。

采纳的回答

Birdman
Birdman 2018-3-2
编辑:Birdman 2018-3-2
Add a condition to break out of the loop then the while condition is not satisfied as:
while diff > tol
if ismembertol(diff,exact,tol)
break;
end
p = p0 - f(p0)/fp(p0);
diff = abs(p-exact); %stop when our iterate is close to the exact root, pi
p0 = p;
end
  4 个评论
Torsten
Torsten 2018-3-2
Just print the p-values.
My guess is that p->0, not ->pi.
Best wishes
Torsten.

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by