how to recursively code the bisection algorithm
25 次查看(过去 30 天)
显示 更早的评论
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
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?
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!