Page 201 - Applied Numerical Methods Using MATLAB
P. 201

190    NONLINEAR EQUATIONS

            function [x,fx,xx] = secant(f,x0,TolX,MaxIter,varargin)
            % solve f(x)=0by using the secant method.
            %input : f  = ftn to be given as a string ’f’ if defined in an M-file
            %       x0  = the initial guess of the solution
            %       TolX  = the upper limit of |x(k) - x(k - 1)|
            %       MaxIter = the maximum # of iteration
            %output: x   = the point which the algorithm has reached
            %       fx   = f(x(last)), xx = the history of x
            h = 1e-4; h2 = 2*h; TolFun=eps;
            xx(1) = x0;  fx = feval(f,x0,varargin{:});
            fork=1: MaxIter
               if k <= 1, dfdx = (feval(f,xx(k) + h,varargin{:})-...
                                 feval(f,xx(k) - h,varargin{:}))/h2;
                else  dfdx = (fx - fx0)/dx;
               end
               dx = -fx/dfdx;
               xx(k + 1) = xx(k) + dx; %Eq.(4.5.2)
               fx0 = fx;
               fx = feval(f,xx(k+1));
               if abs(fx) < TolFun | abs(dx) < TolX,  break; end
            end
            x = xx(k + 1);
            if k == MaxIter, fprintf(’The best in %d iterations\n’,MaxIter), end



              This secant iterative formula is cast into the MATLAB routine “secant()”,
           which never needs anything like the derivative as an input argument. We can
           use this routine “secant()” to solve a nonlinear equation like that dealt with
           in Example 4.2, by typing the following statement into the MATLAB command
           window. The process is depicted in Fig. 4.5.

            >>[x,err,xx] = secant(f42,2.5,1e-5,50) %with initial guess 1.8


                    2.5
                     2
                    1.5
                     1
                    0.5
                                    x 5  x   x              x
                     0                  3     2              0
                         x 1       x 4
                   −0.5

                    −1
                   −1.5
                    −2
                        1.8  1.9   2   2.1  2.2   2.3  2.4  2.5  2.6
                      Figure 4.5  Solving a nonlinear equation by the secant method.
   196   197   198   199   200   201   202   203   204   205   206