Bisection Method // Matlab code

Posted: January 31, 2012 by muhammadakif in Algorithms
Tags: ,
format long;
x = sym('x');
expr = input('Please enter the equation : ');
fx = sym(expr);

x1 = input('Please enter value of X1 : ');
x2 = input('Please enter value of X2 : ');
iter = input('Please enter number of Iterations : ');

fx1 = subs(fx,x,x1);
fx2 = subs(fx,x,x2);

x3 = 0;
counter = 0;

fid=fopen('c:\bisection.csv','w');
fprintf(fid,'%s\n','Iteration,x1,x2,x3,F(x1),F(x2),F(x3),Max Errors');

if fx1*fx2 >= 0
    message = 'x1 and x2 values are not valid for desired root';
    disp(message)
else 

   while ((counter == 0 || abs(x1-x2) > 0.000001 || subs(fx,x,x3) == 0) && counter <= iter)
       counter = counter + 1;

       x3 = (x1 + x2) / 2;   

       fprintf(fid,'%d,',counter);
       fprintf(fid,'%5.8f,',x1);
       fprintf(fid,'%5.8f,',x2);
       fprintf(fid,'%5.8f,',x3);
       fprintf(fid,'%5.8f,',subs(fx,x,x1));
       fprintf(fid,'%5.8f,',subs(fx,x,x2));
       fprintf(fid,'%5.8f,',subs(fx,x,x3));
       fprintf(fid,'%5.8f\n',abs((x2-x1)/(2^counter)));

       x3 = (x1 + x2) / 2;
       if subs(fx,x,x3) * subs(fx,x,x1)< 0
           x2 = x3;
       else
           x1 = x3;
       end    
   end    
end    

sprintf('The root of the equation using Bisection method is :: %d', x3)

fclose(fid);
About these ads
Comments
  1. I had been a little confused at first, fortunately I definitely see your viewpoint.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s