To learn MATLAB, I'm working on a program that finds root of the zero using the Secant Method. Below my code:
function [zero, x_vector] = secant_method(fx, x1, x2, nmax, tol)
%function that tries to find root of given function using the secant method.
%Mandatory inputs: FX is the function to be evaluated, X1 is first input
%value of the function, X2 is second input value of the function.
%Optional inputs: NMAX is maximum number of iterations (default = 5000), tol
%is maximum tolerance (default = 1e-4).
%Outputs: ZERO is the root of the function within the tolerance or after
%the maximum iterations has been reached, X_VECTOR is a vector of all
%consecutive evaluted inputs of the function.
%code by Steven
if ~exist('tol')
tol = 1e-4;
end
if ~exist('nmax')
nmax = 5000;
end
y_vector = [];
x_vector = [];
x_vector(1)=x1;
x_vector(2)=x2;
diff=tol+1; %this ensures at least one iteration will take place
i=1;
while diff > tol && i < (nmax)
i = i+1;
%Creating new straight line from two previous coordinates, using the conventional
% y=ax+b for paramter notation.
y_vector(i-1) = feval(fx,x_vector(i-1));
y_vector(i) = feval(fx,x_vector(i));
a = (y_vector(i)-y_vector(i-1))/(x_vector(i)-x_vector(i-1));
b = y_vector(i)-a*x_vector(i);
x_vector(i+1) = -b/a;
diff = abs(x_vector(i+1)-x_vector(i));
end
if i == (nmax) && diff > tol
fprintf(['Function stopped without converging to the desired tolerance\n',...
'because the number of maximum iterations was reached.']);
end
zero = x_vector(i+1);
return
Now for most inputs, the code works fine. As an example
secant_method('sin', 1, 5, 50, 1e-10) = 3.141592653589793
which is close enough to pi
.
But with some inputs, I don't see why the code returns what it does. For example
secant_method('sin', -8, 12, 500, 1e-10) = 2.002170932439574e+30
but
sin(2.002170932439574e+30)= 0.019481942752609
which is not really close to0
.
Any ideas on why this happens or where I go wrong are much appreciated.
Secant Method rules
if fx(x1) < 0 ---> choose x2 such as fx(x2) > 0
if fx(x1) > 0 ---> choose x2 such as fx(x2) < 0
Example 1:
x1 = 1; sin(x1) = 0.8415;
x2 = 5; sin(x2) = -0.9589;
fx(x1) > 0; fx(x2) < 0
No problem
Example 2:
x1 = -8; sin(x1) = -0.9894;
x2 = 12; sin(x2) = -0.5366;
fx(x1) < 0; fx(x2) < 0
Change the boundary values