Bisection method while loop help

4 vues (au cours des 30 derniers jours)
Isaac Soria
Isaac Soria le 3 Sep 2022
Commenté : Isaac Soria le 3 Sep 2022
function [cVec,n] = bisection_method(f,a,b,tol)
[cVec] = [];
if f(a)*f(b)>0 % Return empty vector and n=0 if f(a)f(b)=0
cVec = [];
n=0;
return
end
n=0;
while (b-a)/2>tol
m=(b+a)/2;
if f(m)==0
c=m;
break
end
if f(a)*f(m)>0
a=m;
end
if f(a)*f(m)<0
b=m;
end
c=m;
n=n+1;
cVec(n)=m;
end
The code nearly works as desired on matlab grader, except it returns a vector [1.5,1.25,1.375] instead of [1.5,1.25,1.375, 1.3125] when I use the following code to call the function
f = @(x) (x.^3 + 4*x.^2 -10);
a = 1;
b = 2;
tol = 10^-1;
[c,n] = bisection_method(f,a,b,tol)
I have noticed that using a smaller tol value of 0.05 will return the desired vector, but I need to use 0.1. Any help is appreciated.

Réponse acceptée

Matt J
Matt J le 3 Sep 2022
while (b-a)>tol

Plus de réponses (0)

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by