secant Algorithm
The secant algorithm is an iterative numerical method used to approximate the root of a real-valued function. It is a powerful and efficient technique for solving mathematical equations, particularly for problems where analytical solutions are not readily available. The algorithm is based on the idea of using secant lines, which are straight lines that intersect two points on the curve of a given function, to approximate the root. Unlike the Newton-Raphson method, which requires knowledge of the derivative of the function, the secant method only needs the values of the function at two initial points to begin the iterative process. This makes the secant algorithm advantageous for functions whose derivatives are difficult or computationally expensive to calculate.
To implement the secant algorithm, one must start with two initial guesses, x0 and x1, that are reasonably close to the true root of the function. The algorithm then proceeds iteratively, using the secant line that passes through the points (x0, f(x0)) and (x1, f(x1)) to generate a new approximation x2 for the root. This process is repeated until a predetermined stopping criterion, such as a maximum number of iterations or a desired level of precision, is met. At each iteration, the older of the two previous approximations is discarded and replaced with the new approximation, and the secant line is recalculated using only the two most recent approximations. Although the secant algorithm can converge faster than other methods like the bisection method, it does not guarantee convergence for all functions or initial guesses, and can occasionally diverge or converge to a different root than intended. However, with proper selection of initial points and a suitable function, the secant algorithm is a powerful tool for finding solutions to mathematical equations.
%Extremely similar to the false position method. The main difference is
%that the secant method does not actually have a defined interval where
%the root lies on. It converges faster than the false position method,
%but it is not always guaranteed to converge.
%INPUTS:
%Function handle f
%x1 = a
%x2 = b
%maximum tolerated error
%OUTPUTS:
%An approximated value for the root of f.
%Written by MatteoRaso
function y = secant(f, a, b, error)
x = [a, b];
n = 2;
while abs(f(x(n))) > error
x(n + 1) = -f(x(n)) * (x(n) - x(n - 1)) / (f(x(n)) - f(x(n - 1))) + x(n);
n = n + 1;
disp(f(x(n)))
endwhile
A = ["The root is approximately ", num2str(x(n))];
disp(A)
y = x(n);
endfunction