Secant Method algorithm in Matlab :
function [xvect,xdif,fx,nit] = secant(x1,x0,nmax,fun,toll);
% SECANT Do the secant iteration to find the zeros of the given
% inline scalar function and its derivative.
% [XVEC,XDIF,FX,NIT] = SECANT(X1,X0,NMAX,FUN,TOLL)
% Input:x0 and x1 starting value
% nmax: maximum number of iteration
% toll: tolerance, default is 1e-10
% fun: given inline function
%
% Output: xvect: stores values in all iterations (arg)
% xdif : difference between two successive values
% (arg)
% fx: stores function values in all iterations
% nit: number of iteration required
%
% Examples:
% fun=inline('x^3+x^2-4'); x0=0.3;x1=0.5; nmax=100;
% fun=inline('x^5+10*x^2-9*x+10');
% Author: Bishnu Lamichhane, University of Stuttgart
if (nargin==4) toll=1e-10; end
x=x1;
fx1=feval(fun,x);
xvect=[x];
fx=[fx1];
x=x0;
fx0=feval(fun,x);
xvect=[xvect;x];fx=[fx;fx0];err=toll+1;nit=0;xdif=[];
while(nit<nmax & err>toll)
nit=nit+1;
if (abs(fx0-fx1)<eps)
err=toll*1e-10;
disp('Stop for vanishing dfun');
else
x=x0-fx0*(x0-x1)/(fx0-fx1);
xvect=[xvect;x];
fnew=feval(fun,x);
fx=[fx;fnew];
err=abs(x0-x);
xdif=[xdif;err];
x1=x0;fx1=fx0;x0=x;fx0=fnew;
end;
end;
n=1:nit;
plot(n, xdif, '-*');
title(['Plot of error with respect to iteration, f(x)=',char(fun)]);
xc = get(gca,'XLim');
yc = get(gca,'YLim');
xc = (xc(1)+xc(2))/2;
text(xc,yc(2)*0.9,['x_{zero} = ',num2str(x)], ...
'HorizontalAlignment', 'center');
|
No comments:
Post a Comment