Borrar filtros
Borrar filtros

What is causing this to have an infinite loop??

2 visualizaciones (últimos 30 días)
Phi Tran
Phi Tran el 2 de Mzo. de 2018
Comentada: Guillaume el 2 de Mzo. de 2018
%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 comentarios
KL
KL el 2 de Mzo. de 2018
Editada: KL el 2 de Mzo. de 2018
If you have access to symbolic math toolbox, I'd suggest vpa/digits.
Guillaume
Guillaume el 2 de Mzo. de 2018
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.

Iniciar sesión para comentar.

Respuesta aceptada

Birdman
Birdman el 2 de Mzo. de 2018
Editada: Birdman el 2 de Mzo. de 2018
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 comentarios
Torsten
Torsten el 2 de Mzo. de 2018
Just print the p-values.
My guess is that p->0, not ->pi.
Best wishes
Torsten.
Phi Tran
Phi Tran el 2 de Mzo. de 2018
thanks

Iniciar sesión para comentar.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!

Translated by