MATLAB: What is causing this to have an infinite loop?

infinite loopnewton's methodwhile loop

%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

Best Answer

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