我是 MATLAB 的新手,在作业中遇到了问题。分配是使用平分法。我最初的代码是:
a = -0.5;
b = 1.1;
f=@(x) x^5-2*x^4+3*x^3-2*x^2+x-1-cos(30*x);
val1 = f(a);
val2 = f(b);
p1a1 = val1*val2;
save('A1.dat','p1a1','-ascii')
%bisection
for i = 0:100
c = (a+b)/2;
if f(c) >= -0.000000001 && f(c) <= 0.000000001
answer = c;
elseif f(c) > 0
b = c;
else a = c;
end
end
answer = c;
save('A2.dat','answer','-ascii')
但是,我需要计算它所花费的迭代次数,所以我将代码的第二部分(在"平分"之后(更改为:
tolerance = 0.000000001;
count = 0;
c =(a+b)/2;
while abs(f(c))>tolerance
count=count+1;
if f(c) > 0
b = c;
else
a = c;
end
end
answer = c;
其中 c 将显示函数的零,在规定的公差范围内。但是,新代码将无法运行,我似乎无法弄清楚我哪里出错了。如果很简单,请道歉
您不会在循环中更新c
的值,它永远不会更改,这意味着您被困在while
循环中。将c = (a+b)/2
定义复制到循环内部,就像以前一样。
c = (a+b)/2;
while abs(f(c))>tolerance
count=count+1;
if f(c) > 0
b = c;
else
a = c;
end
c = (a+b)/2; % <<<<<< This is needed to avoid an infinite loop!
end
answer = c;
平分法保证收敛到根(如果存在(,但您应该小心数值方法的while
循环。特别是,添加最大迭代计数器
maxIters = 1000;
c = (a+b)/2;
while abs(f(c)) > tolerance && count < maxIters
% Code as before ...
end