Code is stuck in infinite loop

7 vues (au cours des 30 derniers jours)
haif hamza
haif hamza le 14 Avr 2020
Commenté : haif hamza le 15 Avr 2020
Trying to find to roots of the function in my code using the incremental search method, but it looks like the code is stuck looping in one condition.
dx=0.1; epsi=0.01; Xi=0.1; Xm=4.0;
F = @(x) 1+5.25*x-sec(sqrt(0.68*x));
a=Xi;
f1=F(a);
b=a+dx;
f2=F(b);
while a<Xm
a=Xi;
f1=F(a);
b=a+dx;
f2=F(b);
if abs(f2) > (1/epsi)
disp ('function approaching infinity at ',a);
a = a+epsi;
f1=F(a);
b=a+dx;
f2=F(b);
else
if f1*f2 == 0
disp ('X is a root',a);
a = a+epsi;
f1=F(a);
b=a+dx;
f2=F(b);
elseif f1*f2 > 0
if a>Xm
break;
else
a=b;
f1=F(a);
b=a+dx;
f2=F(b);
end
else
if dx < epsi
disp ('X is a root',a);
a = a+epsi;
f1=F(a);
b=a+dx;
f2=F(b);
else
a=a-dx;
dx = dx/10;
f1=F(a);
b=a+dx;
f2=F(b);
end
end
end
end

Réponses (1)

Geoff Hayes
Geoff Hayes le 14 Avr 2020
haif - part of the problem (of why you are getting stuck in an infinite loop) is due to
dx=0.1;
epsi=0.01;
Xi=0.1; % <----- set here only
Xm=4.0;
F = @(x) 1+5.25*x-sec(sqrt(0.68*x));
a=Xi; % <------ a initialized to Xi
f1=F(a);
b=a+dx;
f2=F(a)
while a<Xm
a=Xi; % <------ a reset to static Xi
On each iteration of the loop, the code is always re-assigning a to Xi and since the latter is only set outside the loop, then we are always repeating the same iteration again and again. Try commenting out this line and re-running your code. You'll probably also have a problem with
disp ('function approaching infinity at ',a);
with a "too many input arguments" error. Just change this to
disp (sprintf('function approaching infinity at %f',a));
  1 commentaire
haif hamza
haif hamza le 15 Avr 2020
Thank you, your solution worked. For the second problem i used fprintf

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by