Use while for bisection method

조회 수: 24 (최근 30일)
Omed Zewar
Omed Zewar 2017년 12월 5일
답변: Kautuk Raj 2023년 6월 2일
Hi i want a program to bisection method by while
  댓글 수: 2
Walter Roberson
Walter Roberson 2017년 12월 5일
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 2023년 6월 2일
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);

댓글을 달려면 로그인하십시오.

답변 (1개)

Kautuk Raj
Kautuk Raj 2023년 6월 2일
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);

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by