Welcome to the World of Modelling and Simulation

What is Modelling?

This blog is all about system dynamics modelling and simulation applied in the engineering field, especially mechanical, electrical, and ...

A MATLAB Program to Determine the Roots of Equation by Secant method

Problem: Solve the following problem by Secant Method.

f(x) = x - 2e^-x

Determine the roots of the above function where x1 = 0 and x2 = 1.


Solution: The following MATLAB program solves this problem.

% Definition of a function "secantmethod" to solve equation by Secant Method

function [x,ea] = secantmethod(X,X0,etol)

format long;

% Input: X=0, etol=Tolerance definition for error
% Output x=Solution of equation, ea=Calculated error in loop

% Program Initialization

% Iterative Calculations

while (1)
   
    % Implementation of Secant Method
         
    solution = X-((X-(2*exp(-X)))*(X0-X))/((X0-(2*exp(-X0)))-(X-(2*exp(-X))));    
   
    solutionprevious=X;
    X0=X;
    X=solution;
                 
if (solution-solutionprevious)~=0          % Approximate percent relative error
                                
   ea=abs((solution - solutionprevious)/solution)*100;
      
end

if ea<=etol                 
  
    break,               
end

%x0=solutionprevious;
x = solution;

%disp(x0);
disp(x);

end

% Display of output parameters

disp(x);                     

disp(ea);

%disp(solution-(0.1*abs(ea)*solution));

end


Program Outputs:

>> secantmethod(1,0,1e-10)

   0.883298154248460

   0.851584208519236

   0.852612692886131

   0.852605503703827

   0.852605502013723

   0.852605502013723

     3.125167797776517e-13


ans =

   0.852605502013723


#SecantMethod

No comments:

Post a Comment