Use while for bisection method

25 Ansichten (letzte 30 Tage)
Omed Zewar
Omed Zewar am 5 Dez. 2017
Beantwortet: Kautuk Raj am 2 Jun. 2023
Hi i want a program to bisection method by while
  2 Kommentare
Walter Roberson
Walter Roberson am 5 Dez. 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 am 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);

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Kautuk Raj
Kautuk Raj am 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);

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by