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.
0 个评论
采纳的回答
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!