Bisectional method Not always giving correct roots
Afficher commentaires plus anciens
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);
Réponses (1)
Geoff Hayes
le 17 Fév 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 commentaires
Anthony Ming
le 17 Fév 2019
Modifié(e) : Anthony Ming
le 17 Fév 2019
Anthony Ming
le 17 Fév 2019
Geoff Hayes
le 17 Fév 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
le 17 Fév 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
le 17 Fév 2019
Anthony Ming
le 17 Fév 2019
Geoff Hayes
le 17 Fév 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
le 17 Fév 2019
Anthony Ming
le 17 Fév 2019
Geoff Hayes
le 17 Fév 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.
Catégories
En savoir plus sur Variables dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!