Use while for bisection method

25 views (last 30 days)
Omed Zewar
Omed Zewar on 5 Dec 2017
Answered: Kautuk Raj on 2 Jun 2023
Hi i want a program to bisection method by while
  2 Comments
Walter Roberson
Walter Roberson on 5 Dec 2017
That is the normal method of programming bisection method. You can find a number of postings about bisection method if you search.
Vidhi Agarwal
Vidhi Agarwal on 2 Jun 2023
Please find the attached Bisection method code using while loop
You can also refer to this article for reference
% Define the function f(x)
f = @(x) x^3 - 1.6*x^2 - 2.4*x + 0.3;
% Define the interval [a,b]
a = -1;
b = 3;
% Define the tolerance (the maximum error allowed)
tol = 1e-6;
% Set the maximum number of iterations
max_iter = 1000;
% Initialize the variables
iter = 0;
midpoint = (a + b) / 2;
fa = f(a);
fb = f(b);
% Use a while loop to iteratively refine the midpoint
while abs(f(midpoint)) > tol && iter < max_iter
midpoint = (a + b) / 2;
fm = f(midpoint);
if fm == 0
break;
elseif sign(fm) == sign(fa)
a = midpoint;
fa = fm;
else
b = midpoint;
fb = fm;
end
iter = iter + 1;
end
% Display the results
fprintf('The midpoint of the function f(x) = x^3 - 1.6x^2 - 2.4x + 0.3 is: %f\n', midpoint);

Sign in to comment.

Answers (1)

Kautuk Raj
Kautuk Raj on 2 Jun 2023
The bisection method is a numerical algorithm used to find the roots of a function within a specified interval. This is an example code in MATLAB that implements the bisection method:
% Define the function to find the root of
f = @(x) x^3 - 2*x - 5;
% Define the interval to search for the root in
a = 2;
b = 3;
% Set the tolerance and maximum number of iterations
tol = 1e-6;
max_iter = 100;
% Initialize the iteration counter and the bracketing interval
n_iter = 0;
c = (a + b) / 2;
% Loop until the desired tolerance or maximum number of iterations is reached
while abs(f(c)) > tol && n_iter < max_iter
% Evaluate the function at the midpoint of the interval
c = (a + b) / 2;
fc = f(c);
% Check which half of the interval to keep and update the interval
if fc*f(a) < 0
b = c;
else
a = c;
end
% Update the iteration counter
n_iter = n_iter + 1;
end
% Display the result
fprintf('Root found after %d iterations: %f\n', n_iter, c);

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!