大家好,我在为算法编写编程代码时遇到了一个问题,如下所示
当定义为(当前近似-先前近似)/current近似的近似误差小于0.01时,该程序将被终止。它可以简化为(f(xr)i+1 - f(xr)i)/f(xr)i+1。下面是我写的代码,我真的想知道如何编写当满足上述情况时将停止的迭代。
xl = input('Enter lower limit : ');
xu = input('Enter upper limit : ');
xr = (xl+xu)/2;
R = 3; V = 30;
fl = (pi*R*xl^2)-(pi*(xl^3)/3)-V; % between is there anyway can call these functions
fu = (pi*R*xu^2)-(pi*(xu^3)/3)-V; other than typing 3 times
fh = (pi*R*xr^2)-(pi*(xr^3)/3)-V;
while relative error is less than 0.01 then display value of xr
if fl*fu<0
xu = xr;
elseif fl*fu>0
xl = xr;
end
end发布于 2013-03-05 00:33:15
我更新了代码,现在我可以运行它了。我用f(x)=x^2-2来测试它。它在6次迭代中收敛到1.4141。我建议您将这些代码与您之前必须了解的代码进行比较,以了解哪些代码对您无效。这将是一次很好的学习经历。
>> example(1,2);
Crossing found after 6 iterations: 1.414062其中example.m如下所示:
function xr = root(xl,xu)
MAX_NUMBER_ITERATIONS = 1000;
MAX_DELTA=.01;
numberIterations=0;
xr_old=xu;
xr = (xl+xu)/2;
while ((numberIterations<MAX_NUMBER_ITERATIONS) & (abs(xr_old-xr)>=MAX_DELTA))
numberIterations=numberIterations+1;
xr_old = xr;;
product=f(xl)*f(xr);
if product<0
xu = xr;
xr = (xl+xu)/2;
continue;
elseif product>0
xl = xr;
xr = (xl+xu)/2;
continue;
else
break;
end
end
fprintf('Crossing found after %d iterations: %f\n',numberIterations,xr)
end
function y = f(x)
y=x^2-2;
end发布于 2013-03-05 00:28:31
您忘记了执行步骤3(c)。
您也没有按照说明在步骤3(a)和3(b)中“返回到步骤2”。要做到这一点,您将需要按照here所述创建一个while循环;在您的while循环中加入使其保持循环的条件。如果该条件的计算结果为false,则应根据步骤3(c)退出循环。
使用CONTINUE来完成步骤3(a)和3(B)中的“返回到步骤2”部分;这会将执行移回循环的顶部。另请参阅Jump command in MATLAB
祝好运。
发布于 2013-03-05 00:31:26
您可以将计算放入一个函数中:
function f = some_function(x)
R = 3;
V = 30;
f = (pi*R*x^2)-(pi*(x^3)/3)-V; 你可以尝试100次(为了安全):
for i=1:100
xr_old = xr
fr_old = fr
xr = (xl+xu)/2;
fr = some_function(xr);
if abs((xr - xr_old)/xr) < MIN_STEP
break
end
temp = fl*fr
if temp < 0:
xu = xr
fu = fr
else if temp > 0:
xl = xr
fl = fr
end
endhttps://stackoverflow.com/questions/15206036
复制相似问题