Bisection method code - question.

Hi, I wrote the following function for solving V=L[arccos(h/r)r^2 - h(r^2-h^2)^0.5] using the bisection method. However, as I execute the program it gets stuck, yet I cannot figure out why. I'd appreciate any comments.
function h = volume(V,L,r,h1,h2)
h=(h1+h2)/2;
err=abs(V-L*(acosd(h/r)*r^2-h*sqrt(r^2-h^2)));
while (err > 0.01)
if (V-L*(acosd(h1/r)*r^2-h1*sqrt(r^2-h1^2))*(V-L*(acosd(h/r)*r^2-h*sqrt(r^2-h^2))) < 0)
h2=h;
else
h1=h;
end
h=(h1+h2)/2;
err=abs(V-L*(acosd(h/r)*r^2-h*sqrt(r^2-h^2)));
end

답변 (1개)

Matt J
Matt J 2013년 12월 26일

0 개 추천

I think you're just missing some parentheses in
if (V-L*(acosd(h1/r)*r^2-h1*sqrt(r^2-h1^2))*(V-L*(acosd(h/r)*r^2-h*sqrt(r^2-h^2))) < 0)

댓글 수: 4

Matt J
Matt J 2013년 12월 26일
편집: Matt J 2013년 12월 26일
It would be easier to read and debug if you calculate "err" using a function instead of repeating its expression all the time,
function h = volume(V,L,r,h1,h2)
err=@(h) abs(V-L*(acosd(h/r)*r^2-h*sqrt(r^2-h^2))); %anonymous func
h=(h1+h2)/2;
while (err(h) > 0.01)
if err(h1)*err(h) < 0
h2=h;
else
h1=h;
end
h=(h1+h2)/2;
end
end
Matt J
Matt J 2013년 12월 26일
편집: Matt J 2013년 12월 26일
It's also possible that there is no root err(h)=0 in the interval [h1,h2].
Your code does nothing to check, for example that err(h1)*err(h2)<0 for the initial h1, h2.
Yuval
Yuval 2013년 12월 26일
편집: Yuval 2013년 12월 26일
Okay, now the following code doesn't get stuck but the answer seems to be inaccurate. Any idea why?
function h = volume(V,L,r,h1,h2)
h=(h1+h2)/2;
err=abs(V-L*(acosd(h/r)*r^2-h*sqrt(r^2-h^2)));
while (err > 0.01)
if ((V-L*(acosd(h1/r)*r^2-h1*sqrt(r^2-h1^2)))*(V-L*(acosd(h/r)*r^2-h*sqrt(r^2-h^2))) < 0)
h2=h;
else
h1=h;
end
h=(h1+h2)/2;
err=abs(V-L*(acosd(h/r)*r^2-h*sqrt(r^2-h^2)));
end
I mean, it keeps giving out h=0.9998, even when I change the while condition to (err > 2.009032E-11), for instance.
Matt J
Matt J 2013년 12월 26일
편집: Matt J 2013년 12월 26일
What data are you using for V,L,r,h1,h2?

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

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

질문:

2013년 12월 26일

편집:

2013년 12월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by