Code is stuck in infinite loop

5 次查看(过去 30 天)
haif hamza
haif hamza 2020-4-14
评论: haif hamza 2020-4-15
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

回答(1 个)

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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by