Thursday, October 24, 2013

MATLAB - Bisection [NEW]


new
% _______________________________ About ___________________________________
% To find root of a given equation by bisection method
% By Mahesha MG, MIT Manipal
% Date: 24/10/2013
% ________________________________Input____________________________________
clc;
clear;
display('Enter the equation. eg: x^2+x-1');
f1=input('Enter a valid MATLAB expression in x : ','s');
e=input('Enter the accuracy : ');
% _____________________To get upper and lower range________________________
x=0;
f0=eval(f1);
if abs(f0)<e
    display('Root of the equation is zero');
else
    i=1;
    while(i)
     x=x+1;
     if (f0*eval(f1))<0
         xl=0;
         xu=x;
         i=0;
     end
     x=-x;
    if (f0*eval(f1))<0
             xl=x;
             xu=0;
             i=0;
     end
    x=abs(x);
    end
  x=xl;
  if eval(f1)<0
      xn=xl;
      xp=xu;
  else
      xn=xu;
      xp=xl;
  end
% ________________________________Bisection________________________________
while (abs(xn-xp)>e)
    x=(xn+xp)/2;
    if eval(f1)<0
        xn=x;
    else
        xp=x;
    end
end
Root=x
end
% _________________________________________________________________________

No comments:

Post a Comment