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일

1 개 추천

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

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Debugging and Improving Code에 대해 자세히 알아보기

질문:

2020년 4월 14일

댓글:

2020년 4월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by