我试图找到方程g(x)=exp(2x)+3x-4的根。我必须这样做,用MATLAB中的二分法。
(0,2)1e-8我已经用MATLAB编写了一些代码,但是,我得到了错误的答案,它并没有停止计算,这似乎是一个无限循环。
首先,这是我的代码:
g = @(x) (exp(2*x)+3-4);
xl = input('Enter the first approximation xl:');
xu - input('Enter the first approximation xu:');
acc = input('Enter the value of accuracy:');
while ((g(xl)*g(xu)) > 0)
xl = input('Enter the value of first approximation xl:');
xu = input ('Enter the value of first approximation xu:');
end
while (abs(xu-xl)>acc)
xm = (xl-xu)/2
if (g(xl)*g(xm)<0)
xu = xm;
else
xl = xm;
end
end现在MATLAB给了我:xm = -2,并且一直给我这个值。
如何得到xm的良好近似?我知道应该在0.5左右。
发布于 2018-02-26 10:54:38
在实际的二分法while循环中,您可以执行以下操作
xm = (xl-xu)/2xm设置为xl和xu的中点。因此,您有一个符号错误,并且应该执行
xm = (xl+xu)/2;% xm是xl和xm的中点(或平均值)你说你知道结果应该是0.5,但是一个快速的图可以证明它应该接近1.24,正如上面的校正所示(给出了一个结果1.2425)。

编辑:这应该是一个危险信号如果你知道应该是什么答案!,正如Lindsay指出的,你的g定义有一个错误,应该是
g = @(x) (exp(2*x)+3*x-4); % You previously omitted the 2nd 'x', meaning g(x)=exp(2*x)-12您的代码中的最后一个错误,您必须已经修复了,否则您就不会达到无限循环的程度,这就是应该使用-时xu定义中的=。
所有这些修正后,您将得到预期的0.4737 (“大约0.5")的结果。

https://stackoverflow.com/questions/48986466
复制相似问题