Bisection method not returning any values.
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Matt J
2013-10-16
编辑:Matt J
2013-10-16
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 个评论
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 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!