Code is stuck in infinite loop

5 views (last 30 days)
haif hamza
haif hamza on 14 Apr 2020
Commented: haif hamza on 15 Apr 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

Answers (1)

Geoff Hayes
Geoff Hayes on 14 Apr 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 Comment
haif hamza
haif hamza on 15 Apr 2020
Thank you, your solution worked. For the second problem i used fprintf

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!