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)
% Defining a function to find its roots
y = x.^3 + x.^2 - 5.*x - 3;
No comments:
Post a Comment