Search code examples
matlabnumerical-methodsbisection

Bisection method failing and results in infinite loop


I am trying to find the roots of the equation g(x)=exp(2x)+3x-4. I have to do this, using the bisection method in MATLAB.

  • Initial interval is (0,2)
  • Desired accuracy is 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.

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.

How do I get a good approximation of xm? I know it should be around 0.5.


Solution

  • In your actual bisection method while loop, you do the following

    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. 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)

    plot

    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

    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 =.

    With all of these corrected, you get the desired result of 0.4737 ("around 0.5").

    plot2