简体   繁体   English

二等分法失败并导致无限循环

[英]Bisection method failing and results in infinite loop

I am trying to find the roots of the equation g(x)=exp(2x)+3x-4 . 我试图找到方程式g(x)=exp(2x)+3x-4 I have to do this, using the bisection method in MATLAB. 我必须使用MATLAB中的二分法进行此操作。

  • Initial interval is (0,2) 初始间隔为(0,2)
  • Desired accuracy is 1e-8 所需精度为1e-8

I have written some code in MATLAB, however, I get the wrong answer and it doesn't stop calculating, which seems like an infinite loop. 我已经在MATLAB中编写了一些代码,但是我得到了错误的答案,并且它并没有停止计算,这似乎是一个无限循环。

First, here's my code: 首先,这是我的代码:

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

Now MATLAB gives me: xm = -2 , and continues forever giving me this value. 现在,MATLAB给了我: xm = -2 ,并且一直持续给我这个值。

How do I get a good approximation of xm ? 如何获得xm近似值? I know it should be around 0.5. 我知道应该在0.5左右。

In your actual bisection method while loop, you do the following 在您的实际二等分方法while循环中,执行以下操作

xm = (xl-xu)/2
  • Question: What is this meant to do? 问题:这是什么意思?
  • Answer: It's meant to set xm equal to the midpoint of xl and xu . 答:这意味着将xm设置为等于xlxu的中点。 Therefore you have a sign error, and should be doing 因此,您有符号错误,应该这样做

     xm = (xl+xu)/2; % xm is the midpoint (or mean) of xl and xu 

You said you know the result should be 0.5, but a quick plot can verify it should be nearer 1.24, as the above correction shows (giving a result 1.2425) 您说您知道结果应该为0.5,但是通过快速绘图可以确认结果应该接近1.24,如上述校正所示(给出结果1.2425)

情节

Edit: This should be a red flag if you know what the answer should be! 编辑: 如果您知道答案应该是什么,这应该是一个危险信号! As pointed out by Lindsay, you have a typo in your g definition, it should be 正如Lindsay所指出的,您在g定义中有一个错字,应该是

g = @(x) (exp(2*x)+3*x-4); % You previously omitted the 2nd 'x', meaning g(x)=exp(2*x)-12

A final typo in your code, which you must have fixed or you wouldn't have got as far as the infinite loop, was the - in the definition of xu when you should be using = . 代码中的最后一个错别字,是您必须使用固定的,否则您将无法到达无限循环,这是xu定义中的-当您应使用=

With all of these corrected, you get the desired result of 0.4737 ("around 0.5"). 纠正所有这些问题后,您将获得期望的结果0.4737(“约0.5”)。

情节2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM