today

function root = bisection_method(a, b, tol)
    % Function to find the root of e^x - x - 2 using the bisection method
    
    f = @(x) exp(x) - x - 2;
    
    if f(a) * f(b) > 0
        error('The function does not change sign on the interval [a, b].');
    end
    
    while (b - a) / 2 > tol
        c = (a + b) / 2;
        if f(c) == 0
            break;
        elseif f(c) * f(a) < 0
            b = c;
        else
            a = c;
        end
    end
    
    root = (a + b) / 2;
end

% Example usage:
a = 0; % Lower bound of the interval
b = 2; % Upper bound of the interval
tol = 1e-6; % Tolerance

root = bisection_method(a, b, tol);
fprintf('The root of the equation e^x - x - 2 is approximately %.6f.\n', root);
Share on Google Plus

About THE CHOOSEN

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment