Secant Method for Solving non-linear equations in MATLAB(mfile)



% Secant Algorithm
 % Find the root of y = cos(x) from 0 to pi.



 f = @(x) (cos(x));
 p0 = input('Enter 1st approximation, p0: ');
 p1 = input('Enter 2nd approximation, p1: ');
 n = input('Enter no. of iterations, n: ');


 tol = input('Enter tolerance, tol:  ');

 i = 2;
 f0 = f(p0);
 f1 = f(p1);
 while i <= n


    p = p1-f1*(p1-p0)/(f1-f0);
    fp = f(p);
    if abs(p-p1) < tol
       fprintf('\nApproximate solution p = %11.8f\n\n',p);
       break;
    else
       i = i+1;


       p0 = p1;
       f0 = f1;
       p1 = p;
       f1 = fp;
    end

 end


Output:



>> Secant_method_m
Enter 1st approximation, p0: 1
Enter 2nd approximation, p1: 2
Enter no. of iterations, n: 30
Enter tolerance, tol:  0.0001

Approximate solution p =  1.57079633

>> 





No comments