Bisectional method Not always giving correct roots
Show older comments
My code sometimes does not give correct roots? Sometimes it will and other times it wont depending on the boundaries, please let me know if you guys know what is causing it.
clc
clear all
close all
f=@(x)(x.^3+7*x.^2-33*x-135);
yl = input('type approximated lower boundary:');
yu = input('type approximated upper boundary:');
err=input('Type desired approximate error limit:');
if(f(yl)*f(yu)) > 0
disp('TRY NEW BOUNDARIES');
return
%if values do not produce a negative number give better boundaries
end
while abs(yu-yl) >= err %basically how close do you want the boundaries to go
ynew=(yl+yu)/2;
if (f(yl)*f(yu) < 0)
yu=ynew;
else
yl=ynew;
end
end
fprintf('The root of this equation given your error limit is=%f', ynew);
Answers (1)
Geoff Hayes
on 17 Feb 2019
Anthony - can you provide an example (with inputs) that gives the correct solution and an example that doesn't? Also, don't you need to include the new value, ynew, in your comparison
ynew = (yl + yu) / 2;
if (f(yl) * f(ynew)) < 0
%etc.
end
rather than re-using the upper bound again as
if (f(yl)*f(yu) < 0) % incorrect?
10 Comments
Anthony Ming
on 17 Feb 2019
Edited: Anthony Ming
on 17 Feb 2019
Anthony Ming
on 17 Feb 2019
Geoff Hayes
on 17 Feb 2019
Anthony - I don't understand your inputs: 22,-30,.001. Isn't the first input supposed to be the lower bound on the interval and the second input the upper bound? So shouldn't the order be reversed to -30, 22, 0.001?
Geoff Hayes
on 17 Feb 2019
For your function, there seem to be roots at (at least) -9 and 5. Is this true?
As for your second input set, what happens if you try entering in the order -6, 18, 0.001?
Anthony Ming
on 17 Feb 2019
Anthony Ming
on 17 Feb 2019
Geoff Hayes
on 17 Feb 2019
You may also want to consider
while abs(yu-yl) >= err
Do we need another condition to determine if we are finished? Take a look at Bisection Method algorithm. What other check do they have?
Anthony Ming
on 17 Feb 2019
Anthony Ming
on 17 Feb 2019
Geoff Hayes
on 17 Feb 2019
I think that the equality is needed to handle the case where f(ynew) is zero, like in the article with the If f(c) = 0.
Categories
Find more on Variables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!