【发布时间】:2020-10-18 05:23:31
【问题描述】:
function r=bisection(f,a,b,tol,nmax)
% function r=bisection(f,a,b,tol,nmax)
% inputs: f: function handle or string
% a,b: the interval where there is a root
% tol: error tolerance
% nmax: max number of iterations
% output: r: a root
c=(a+b)/2;
nit=1;
if f(a)*f(b)>0
r=NaN;
fprintf("The bisection method failed \n")
else
while(abs(f(c))>=tol && nit<nmax)
if (f(c)*f(a))<0
c=(a+c)/2;
elseif (f(c)*f(b))<0
c=(a+b)/2;
elseif f(c)==0
break;
end
nit=nit+1;
end
r=c;
end
以上是我的二分法代码。我对为什么该代码不能正常工作感到困惑。 f(c) 的结果在运行时每 3 次重复一次。谁能告诉我为什么这段代码不起作用?
【问题讨论】: