You are on page 1of 3

% Define the function and its derivative

f = @(x) exp(-x) - x;
df = @(x) -exp(-x) - 1;

% Define the interval [a, b] and initial guesses for Newton-Raphson and secant methods
a = 0;
b = 1;
x0 = 0.5;
x1 = 1;

% Define tolerance and maximum number of iterations


tol = 1e-8;
max_iter = 1000;

% Compute the true root of the function


true_root = fzero(f, [a, b]);

% Initialize arrays to store iteration number and true percent relative errors
iterations = 1:max_iter;
errors_bisection = zeros(1, max_iter);
errors_false_position = zeros(1, max_iter);
errors_newton_raphson = zeros(1, max_iter);
errors_secant = zeros(1, max_iter);

% Bisection method
root_bisection = bisection(f, a, b, tol, max_iter);
errors_bisection(1) = abs((root_bisection - true_root) / true_root) * 100;
for i = 2:max_iter
root_bisection = bisection(f, a, b, tol, i);
errors_bisection(i) = abs((root_bisection - true_root) / true_root) * 100;
end

% False position method


root_false_position = false_position(f, a, b, tol, max_iter);
errors_false_position(1) = abs((root_false_position - true_root) / true_root) * 100;
for i = 2:max_iter
root_false_position = false_position(f, a, b, tol, i);
errors_false_position(i) = abs((root_false_position - true_root) / true_root) * 100;
end

% Newton-Raphson method
root_newton_raphson = newton_raphson(f, df, x0, tol, max_iter);
errors_newton_raphson(1) = abs((root_newton_raphson - true_root) / true_root) * 100;
for i = 2:max_iter
root_newton_raphson = newton_raphson(f, df, x0, tol, i);
errors_newton_raphson(i) = abs((root_newton_raphson - true_root) / true_root) * 100;
end

% Secant method
root_secant = secant(f, x0, x1, tol, max_iter);
errors_secant(1) = abs((root_secant - true_root) / true_root) * 100;
for i = 2:max_iter
root_secant = secant(f, x0, x1, tol, i);
errors_secant(i) = abs((root_secant - true_root) / true_root) * 100;
end

% Plot the convergence behavior


figure;
plot(iterations, errors_bisection, 'r-', 'LineWidth', 1.5);
hold on;
plot(iterations, errors_false_position, 'g-', 'LineWidth', 1.5);
plot(iterations, errors_newton_raphson, 'b-', 'LineWidth', 1.5);
plot(iterations, errors_secant, 'm-', 'LineWidth', 1.5);
xlabel('Iteration');
ylabel('True Percent Relative Error (%)');
title('Convergence Behavior of Root Finding Methods');
legend('Bisection', 'False Position', 'Newton-Raphson', 'Secant');
grid on;
hold off;

You might also like