Bisection method while loop help
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Isaac Soria
am 3 Sep. 2022
Kommentiert: Isaac Soria
am 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.
0 Kommentare
Akzeptierte Antwort
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!