% Clearing Screen
clc %clears the Command Window
% Setting x as symbolic variable
syms x; % syms is used to declare x as a symbolic variable. This allows the user to define and
manipulate mathematical expressions involving x.
% Input Section
y = input('Enter non-linear equations: '); % The user is prompted to input a non-linear equation (as a
function of x). This will be evaluated later.
a = input('Enter first guess: '); % The first guess (lower bound) for the root.
b = input('Enter second guess: '); % The second guess (upper bound) for the root.
e = input('Tolerable error: '); % The tolerable error, which is the threshold for the absolute value of the
function value at the estimated root.
% Finding Functional Value
fa = eval(subs(y,x,a)); % Substitutes the value of a into the function y, creating a new expression.
fb = eval(subs(y,x,b)); % Evaluates this expression numerically to find the function values at a and b,
stored in fa and fb, respectively.
% Implementing Bisection Method
if fa*fb > 0 % This conditional checks if the product of fa and fb is greater than zero. If so, it means
that both guesses are either positive or negative, indicating that there is no root between a and b.
disp('Given initial values do not bracket the root.'); % If this condition is true, a message is
displayed, and the bisection method cannot proceed.
else
c = (a+b)/2; % The midpoint c is calculated as the average of a and b.
fc = eval(subs(y,x,c)); % fc is the function value at c.
fprintf('\n\na\t\t\tb\t\t\tc\t\t\tf(c)\n'); % The output table header is printed for readability,
preparing to display the values of a, b, c, and f(c) in each iteration.
while abs(fc)>e % This while loop continues until the absolute value of fc is less than or equal to the
tolerable error e. This means we are looking for the root with sufficient precision.
fprintf('%f\t%f\t%f\t%f\n',a,b,c,fc); % This prints the current values of a, b, c, and f(c) in the
output table.
if fa*fc< 0 % If fa * fc < 0, it means the root is between a and c, so b is updated to c.
b =c;
else
a =c; % Otherwise, the root is between c and b, so a is updated to c.
end
c = (a+b)/2; % The new midpoint c is recalculated, and its function value fc is evaluated again for
the updated bounds.
fc = eval(subs(y,x,c));
end
fprintf('\nRoot is: %f\n', c); % Once the loop exits (indicating that the error tolerance has been
met), the estimated root c is printed as the final output.
end