0% found this document useful (0 votes)
6 views

Bisection Method

This document describes an algorithm to find the root of a function using the bisection method. It provides code to implement the bisection method, and examples applying it to specific functions and intervals to find roots within a given tolerance.

Uploaded by

Ahmed Hosny
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Bisection Method

This document describes an algorithm to find the root of a function using the bisection method. It provides code to implement the bisection method, and examples applying it to specific functions and intervals to find roots within a given tolerance.

Uploaded by

Ahmed Hosny
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Find root using Bisection Method

function [root, ea, iter, logTable] = bisection_method()


% Step 0: Input the function
user_func = input('Enter the function in terms of x: ', 's');
func = str2func(['@(x)' user_func]);
% Step 1: Input lower and upper bounds
xl = input('Enter the lower bound (xl): ');
xu = input('Enter the upper bound (xu): ');
% Check if the function changes sign over the interval
if func(xl) * func(xu) >= 0
error('The function must change sign over the interval. Please choose different
bounds.');
end
% Step 2: Initialize variables
iter = 0;
% Store the desired tolerance
tolerance = input('Enter the desired tolerance (es): ');
% Store the maximum number of iterations
maxIterations = input('Enter the maximum number of iterations (imax): ');
ea = 100; % Initial approximation error (set to a large value)
logTable = [];
fprintf('Iteration xl xu xr f(xl) f(xu) f(xr) ea\n');
% Step 3: Bisection method iterations
while ea >= tolerance && iter < maxIterations
xr = (xl + xu) / 2;

if xr ~= 0
ea = abs((xr - xl) / xr) * 100;
else
ea = 0;
end

% Log current iteration information


logTable = [logTable; iter, xl, xu, xr, func(xl), func(xu), func(xr), ea];

% Display current iteration information


fprintf('%4d %.6f %.6f %.6f %.6f %.6f %.6f %.6f\n', iter, xl,
xu, xr, func(xl), func(xu), func(xr), ea);

% Update bounds based on the sign of the function


if func(xl) * func(xr) < 0
xu = xr;
elseif func(xl) * func(xr) > 0
xl = xr;
else
ea = 0;
end

iter = iter + 1;
end

root = xr;
end
Find root using Bisection Method

1. Consider the equation 𝑓(𝑥) = cos(𝑥) − sin(3𝑥) = 0 which has many roots. Use the above code to find a root in the initial
interval [0, 0.5]. Perform the computations until percentage approximate relative error ( a(%)) is less than 2%. Fill the
following table.

2. Repeat step 1 until percentage approximate relative error is less than 0.2%.
Find root using Bisection Method

3. Repeat step 1 using the initial interval [-3, -2.5]

You might also like