Bisection method not returning any values.

So, I've written the following code for the bisection method, however it doesn't seem to be returning any values.
function [r, n] = bisection(a,b,f,tol)
if (f(a)*f(b) > 0)
error('Invalid choice of interval');
end
r = 0;
n = 0;
while ((b - a)/2 > tol)
n = n + 1;
r = (a + b)/2;
if(f(r) == 0)
break;
elseif (f(a)*f(b) < 0)
b = r;
else
a = r;
end
end
I'm using it with inputs of (0,1,q,0.5) I also tried tol as 0.1 too. q is some anonymous function that I defined, in this case it's q(x) = 3x - 1. Like, I type the command Bisection(0,1,q,0.5) and it executes without returning an error but doesn't return any numerical values whatsoever. Any ideas why this is?

 채택된 답변

Matt J
Matt J 2013년 10월 16일
편집: Matt J 2013년 10월 16일

1 개 추천

Works fine for me. It returns the wrong value, but you can fix that by changing f(a)*f(b) < 0 to f(a)*f(r) < 0.

댓글 수: 5

David
David 2013년 10월 16일
편집: David 2013년 10월 16일
That's strange. Thanks for pointing out that error, by the way. Are you inputting it in anyway different to the way I am? I mean, are using a different anonymous function or anything like that? For example, if i write the following code:
q = @(x) 3*x - 1;
Bisection(0,2,q,0.5)
Using the exact code for Bisection as above, bar the change that you suggested, the only value I'm getting returned to me is 1. Nothing else, just 1.
Your function has two outputs, so you want to call it with
[r,n] = Bisection(0,2,q,0.5)
David
David 2013년 10월 16일
That was fairly stupid of me. Thanks for the help.
David
David 2013년 10월 16일
Actually, one further question. If I enter a quadratic equation, which may have 2 distinct roots,is there anyway to get it to output both roots? Or, would this be a much more complicated program.
Matt J
Matt J 2013년 10월 16일
편집: Matt J 2013년 10월 16일
No, there is no general algorithm for finding "all" roots of a general function without at least knowing in advance a lower bound on the spacing between the roots.
I assume, by the way, that this is just a homework exercise. In reality, you would never use your own home-brewed bisection algorithm. You would just use FZERO. So, there is no obvious rationale for giving this code more capabilities then the homework assignment requests.

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

추가 답변 (0개)

카테고리

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

태그

질문:

2013년 10월 16일

댓글:

2013년 10월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by