Code is stuck in infinite loop
조회 수: 4 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
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));
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!