Effacer les filtres
Effacer les filtres

Bisection method- code stops after one iteration

2 vues (au cours des 30 derniers jours)
MG
MG le 4 Déc 2015
Commenté : MG le 4 Déc 2015
Hi, my code doesn't seem to continue beyond the first iteration of the bisection method in my loop. I also am not getting the right answer. I'm not sure where the mistake is.
function c = findroot(f,a,b,e)
% a is the initial value
% b is the final value
% e is the tolerance
if f(a)*f(b)>0
error('f(a) and f(b) must have opposite signs')
end
c = (a+b)/2;
while abs(b-c) <= e;
f = f(c);
break
if f(a)*f(c) <= 0;
c = b;
f(c) = f(b);
else
c = a;
f(c) = f(a);
end
end
end
I am calling the following in the command window:
>> f = @(x) x.^2-x-1;
>> findroot(f, 1, 2, 0.001)

Réponse acceptée

Torsten
Torsten le 4 Déc 2015
function c = findroot(f,a,b,e)
% a is the initial value
% b is the final value
% e is the tolerance
left = a;
right = b;
middle = (left+right)/2;
fleft = f(left);
fright = f(right);
fmiddle = f(middle);
if fleft*fright > 0
error('f(a) and f(b) must have opposite signs')
end
while right-left >= e && abs(fmiddle) >= e
if fmiddle*fleft <= 0
right = middle;
fright = fmiddle;
else
left = middle;
fleft = fmiddle;
end
middle = (left+right)/2;
fmiddle = f(middle);
end
c = middle;
end
Best wishes
Torsten.
  1 commentaire
MG
MG le 4 Déc 2015
Hi Torsten. Thank you for the code, I actually figured out the problem myself shortly after posting the question.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Interactive Control and Callbacks dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by