二分法失败并导致无限循环
Bisection method failing and results in infinite loop
我正在尝试求方程 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 左右。
在实际的二分法 while
循环中,您执行以下操作
xm = (xl-xu)/2
- 问:这是什么意思?
答:意思是让xm
等于xl
和xu
的中点。因此你有一个符号错误,应该做
xm = (xl+xu)/2; % xm is the midpoint (or mean) of xl and xu
你说过你知道结果应该是 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 ("around 0.5")。
我正在尝试求方程 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 左右。
在实际的二分法 while
循环中,您执行以下操作
xm = (xl-xu)/2
- 问:这是什么意思?
答:意思是让
xm
等于xl
和xu
的中点。因此你有一个符号错误,应该做xm = (xl+xu)/2; % xm is the midpoint (or mean) of xl and xu
你说过你知道结果应该是 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 ("around 0.5")。