bisection method to determine an approximation to the root that is accurate to at least within 10^-4 in matlab

main.m
function root = bisectionMethod(f, a, b, tolerance)
    % Check for valid inputs
    if f(a) * f(b) >= 0
        error('Function must have opposite signs at the interval endpoints.');
    end
    if a >= b
        error('Interval endpoints must be in increasing order.');
    end
    
    % Perform bisection until desired tolerance is reached
    while abs(a - b) >= tolerance
        c = (a + b) / 2;
        
        % Check if root has been found
        if abs(f(c)) < tolerance
            root = c;
            return;
        end
        
        % Update interval bounds
        if f(a) * f(c) < 0
            b = c;
        else
            a = c;
        end
    end
    
    % Calculate the approximation to the root
    root = (a + b) / 2;
end
757 chars
31 lines

To use the above code, you need to define a function f that represents the equation you want to find the root of. The a and b inputs represent the interval boundaries within which the root is expected to be. The tolerance input specifies the desired accuracy of the root approximation.

Here's an example usage of the bisectionMethod function:

main.m
% Define the function f
f = @(x) x^3 - 2*x - 5;

% Define the interval boundaries
a = 1;
b = 3;

% Specify the desired tolerance
tolerance = 10^(-4);

% Call the bisectionMethod function
root = bisectionMethod(f, a, b, tolerance);

% Display the root approximation
disp(['Root: ', num2str(root)]);
298 chars
16 lines

This code will find an approximation to the root of the function f(x) = x^3 - 2*x - 5 accurate to at least within 10^(-4). Adjust the function definition, interval boundaries, and tolerance as needed for your specific case.

gistlibby LogSnag