how to recursively code the bisection algorithm

조회 수: 6 (최근 30일)
Dimitra
Dimitra 2023년 6월 4일
댓글: Dimitra 2023년 6월 4일
This is how I'm trying to make the code recursive. But I have some errors:
Can you please haelp me?
  댓글 수: 2
John D'Errico
John D'Errico 2023년 6월 4일
When you post a PICTURE of your code, nobody can help you without typing in the code by hand from that picture. This makes it significantly harder to help you, when all you needed to do was to paste in the TEXT directly.
Since text is trival to do, is there a good reason why you want to make it more difficult for you to get help?
Dimitra
Dimitra 2023년 6월 4일
ok i will do it!

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

채택된 답변

Tushar
Tushar 2023년 6월 4일
Hi Dimitra,
I think we can do it like this:
function root = bisection_recursive(f, a, b, tol, max_it)
fa = feval(f, a);
fb = feval(f, b);
% Check if a root is already found
if abs(fa) < tol
root = a;
return;
elseif abs(fb) < tol
root = b;
return;
end
% Check if the interval is valid
if fa * fb > 0
error('No root exists in the given interval.');
end
% Recursive bisection algorithm
function root = bisection_recursive_helper(a, b, x_previous, i)
if i > max_it
error('Maximum number of iterations reached.');
end
x = (a + b) / 2; % Midpoint
fprintf('Iteration %3d: %10.8f\n', i, x);
fx = feval(f, x);
if abs(x - x_previous) < tol || abs(fx) < tol
root = x;
return;
end
if fa * fx < 0
root = bisection_recursive_helper(a, x, x, i + 1);
else
root = bisection_recursive_helper(x, b, x, i + 1);
end
end
% Call the recursive helper function
root = bisection_recursive_helper(a, b, b, 1);
end
To use this function, you need to define your function f and provide the initial interval [a, b], the tolerance tol, and the maximum number of iterations max_it. The function will recursively divide the interval and converge to the root within the specified tolerance or maximum number of iterations.
Here's an example of how you can use the bisection_recursive function to find the root of a function:
% Define your function
f = @(x) x^2 - 4;
% Define the interval [a, b]
a = 1;
b = 3;
% Set the tolerance and maximum number of iterations
tol = 1e-6;
max_it = 100;
% Call the bisection_recursive function
root = bisection_recursive(f, a, b, tol, max_it);
% Display the result
fprintf('Root: %10.8f\n', root);
Make sure to modify the function f and the input parameters a, b, tol, and max_it according to your specific problem.
  댓글 수: 1
Dimitra
Dimitra 2023년 6월 4일
Thank you very much! I will try it right now

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by