MATLAB code for Bisection method

How to run the code:

1. Download the m file and open it in MATLAB.

2. Now there are 6 input arguments and minimum 3 argument is required to run the program.

3. First one is function. You can write the function as below

func=inline(‘-0.5*x^2+2.5*x+4.5’);

or

[email protected](x) -0.5*x^2+2.5*x+4.5;

4. Third and fourth xl and xu which are lower and upper guesses respectively.

5. Fifth one is maximum number of iteration you want to perform.

6. Sixth argument is for desired relative error you want to get.

7. Seventh is an additional parameters used by func.

Now after opening the m file copy the following code and run in the command window.

[email protected](x) -0.5*x^2+2.5*x+4.5;

xl=5;

xu=10;

maxit=2;

[root,ea,iter]=bisect(func,xl,xu,maxit)

Download .m file:

Download .m file

Code:

function [root,ea,iter]=bisect(func,xl,xu,maxit,es,varargin)
% bisect: root location zeroes
% [root,ea,iter]=bisect(func,xl,xu,es,maxit,p1,p2,…):
% uses bisection method to find the root of func
% input:
% func = name of function
% xl, xu = lower and upper guesses
% es = desired relative error (default = 0.0001%)
% maxit = maximum allowable iterations (default = 50)
% p1,p2,… = additional parameters used by func
% output:
% root = real root
% ea = approximate relative error (%)
% iter = number of iterations
if nargin<3,error(‘at least 3 input arguments required’),end
test = func(xl,varargin{:})*func(xu,varargin{:});
if test>0,error(‘no sign change’),end
if nargin<4|isempty(es), es=0.0001;end
if nargin<5|isempty(maxit), maxit=50;end
iter = 0; xr = xl;
while (1)
xrold = xr;
xr = (xl + xu)/2;
iter = iter + 1;
if xr ~= 0,ea = abs((xr – xrold)/xr) * 100;end
test = func(xl,varargin{:})*func(xr,varargin{:});
if test < 0
xu = xr;
elseif test > 0
xl = xr;
else
ea = 0;
end
if ea <= es | iter >= maxit,break,end
end
root = xr;

 

Like us !

Comments