Infintite Loop- bisection search how to stop

function rootx = bisectionSearch (fhandle,a,b,epsilon)
while (b-a) > epsilon %assume a<b
m =(b+a)/2
fhandlem=fhandle(m);
if fhandlem == 0
rootx = m %If f(m) is equal to zero then return the root as m
else if sign (fhandle(m))== sign (fhandle(a)) %
a=m; % If f(m) has the same sign as f(a) Replace a with m
else
m=b;
end
end
end
m;
end
Hi guys this is an infinte loop and I do not know why or how to fix it Please help if possible. when I test it it keeps giving me m values repeatly of 1.75 and I dont think thats even the right answer. please Help!

2 件のコメント

Matt J
Matt J 2012 年 10 月 4 日
It gives you m=1.75 repeatedly with what input arguments?
Michael  Kurniawan
Michael Kurniawan 2012 年 10 月 4 日
[x]=bisectionSearch(f,1,2,0.01) f= @(x)sin(x)-log(x+1)

サインインしてコメントする。

 採用された回答

Matt J
Matt J 2012 年 10 月 4 日
編集済み: Matt J 2012 年 10 月 4 日

0 投票

In the case fhandlem==0, you should BREAK to terminate the loop. Also, you need b=m instead of m=b.
Finally, you could use an ELSEIF structure instead of ELSE...IF.

7 件のコメント

Michael  Kurniawan
Michael Kurniawan 2012 年 10 月 4 日
while (b-a) > epsilon %assume a<b
m =(b+a)/2
fhandlem=fhandle(m);
if fhandlem == 0
break
rootx = m %If f(m) is equal to zero then return the root as m
else if sign (fhandle(m))== sign (fhandle(a)) %
a=m; % If f(m) has the same sign as f(a) Replace a with m
else
m=b;
end
end
end
m;
end
Hello Matt Thank you for your help. Not sure if this is what you meant but I tried this and its still looping.
Matt J
Matt J 2012 年 10 月 4 日
編集済み: Matt J 2012 年 10 月 4 日
You need b=m instead of m=b.
You also still haven't given us input data that we can use to reproduce the problem.
Michael  Kurniawan
Michael Kurniawan 2012 年 10 月 4 日
function rootx = bisectionSearch (fhandle,a,b,epsilon)
while (b-a) > epsilon %#ok<ALIGN> %assume a<b
m =(b+a)/2
fhandlem=fhandle(m);
if fhandlem == 0
break
rootx = m %If f(m) is equal to zero then return the root as m
elseif sign (fhandle(m))== sign (fhandle(a)) %
a=m; % If f(m) has the same sign as f(a) Replace a with m
else
m=b;
end
end
end
Hello Matt is this what you wanted me to do
Matt J
Matt J 2012 年 10 月 4 日
No, never mind. Go back to your previous code and set b=m instead of m=b.
Michael  Kurniawan
Michael Kurniawan 2012 年 10 月 4 日
編集済み: Michael Kurniawan 2012 年 10 月 4 日
No matt you are right I did need to set b=m instead of m=b. The infinite has stopped now
Michael  Kurniawan
Michael Kurniawan 2012 年 10 月 4 日
Thank you!!
Matt J
Matt J 2012 年 10 月 4 日
Move rootx=m to the last line of the function.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by