Bisection method while loop help

4 次查看(过去 30 天)
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.

采纳的回答

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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by