Originally Posted by

**mithilesh** i have created this script file for fniding roots of x^3-x-3 using the secant method.

The secant rule uses the itteration:

$\displaystyle x_{n+1}=x_n-\frac{x_n-x_{n-1}}{f(x_n)-f(x_{n-1})}f(x_n)$

to itterate its way to a solution of $\displaystyle f(x)=0$.

This is almost exactly the same as Newton-Raphson except the explicit derivative of $\displaystyle f(x)$ is replaced by an estimate derived from the last two itterates (or the two initial guesses at start up).

So the code for this is most easily obtained by modifying that for Newton-Raphson:

Code:

function rt=SCNTroot(f,x0,x1,tol)
%================================================
% f the function we wish to find the root of (function handle)
% x0 and x1 two distinct initial guesses at the root
% tol stopping tolerance
%================================================
xx1=x0;xx2=x1;
err=1e6;
while err>tol
fxx1=feval(f,xx1);
fxx2=feval(f,xx2)
xnew=xx2-(xx2-xx1)/(ffx2-fxx1)*fxx2;
err=abs(xnew-xx);
xx1=xx2;xx2=xnew
end
rt=xx2;

If we also wish to return a vector of the itterates we can modify this to:

Code:

function [rt,Vrt]=SCNTroot(f,x0,x1,tol)
%================================================
% f the function we wish to find the root of (function handle)
% x0 and x1 two distinct initial guesses at the root
% tol stopping tolerance
%================================================
xx1=x0;xx2=x1;
Vrt=[x0,x1];
err=1e6;
while err>tol
fxx1=feval(f,xx1);
fxx2=feval(f,xx2)
xnew=xx2-(xx2-xx1)/(ffx2-fxx1)*fxx2;
err=abs(xnew-xx);
xx1=xx2;xx2=xnew
end
rt=xx2;
Vrt=[Vrt,rt];

(note I have not tested this so there may be residual bugs)