Welcome to the World of Modelling and Simulation

What is Modelling?

This blog is all about system dynamics modelling and simulation applied in the engineering field, especially mechanical, electrical, and ...

A MATLAB Program to Find the Roots of a Function by Bisection Method

In this article, a MATLAB program is developed to find the roots of any function by Bisection approach. There are two functions created for this purpose. The first one implements the Bisection method. And the second one is for the function itself, for which, we are interested to find the roots. Let us assume a function,

y = x3 + x2 – 5x – 3

First Function: Bisection Method

function [root,f_x,e_r,iter] = bisectionmethod(func_name,x_lower,x_upper,e_tol,max_iter,varargin)

% INPUTS:

% func_name: input function to find its roots

% x_lower: lower limit of the bracket

% x_upper: upper limit of the bracket

% e_tol: defining error tolerance for this method

% max_iter: Total iteration number

% varargin: to take any number of inputs for the function

% OUTPUTS:

% root: root of the given function

% f_x: function value at the root

% e_r: relative error

% iter: number of iteration taken

close all;

clc;

if nargin < 3  % Defines the number of input function arguments

error('Minimum 3 Input Arguments are Required to Run the Function')

end

% Product of the function at upper & lower interval

product_of_functions = func_name(x_lower,varargin{:}) * func_name(x_upper,varargin{:});

if product_of_functions > 0

error('No Roots Found within the Given Range'),

end

% Logical operator || 'or'

if nargin <4 || isempty(e_tol)

e_tol=0.0001;

end

if nargin <5 || isempty(max_iter)

max_iter=50;

end

% Assuming some parameters to initiate 'while' loop

iter = 0; xr = x_lower; e_r = 1;

while(1)

xrold=xr;

xr=(x_lower + x_upper)/2; % Bi-section Approach

iter = iter + 1;

if xr~=0  % Logical operation ~= 'not equal'

e_r=abs((xr-xrold)/xr);

end

product_of_functions = func_name(x_lower,varargin{:}) * func_name(xr,varargin{:});

if product_of_functions < 0

x_upper = xr;

elseif product_of_functions > 0

x_lower = xr;

else

e_r=0;

end

if e_r <= e_tol || iter >= max_iter

break,

end

end

root = xr;

f_x = func_name(xr, varargin{:});

end

Second Function: The Polynomial (y = x3 + x2 – 5x – 3)

function y = func_example(x)
% Defining a function to find its roots
y = x.^3 + x.^2 - 5.*x - 3;
end

Now, when you are going to call the Bisection Method from the MATLAB command prompt, use the following syntax where the function handle is used to call another function, which is the polynomial in our case.

>> bisectionmethod(@func_example,-100,100)