[英]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(“約0.5”)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.