Secant Method Using C++ with Output

Table of Contents

This program implements Secant Method for finding real root of nonlinear equation in C++ programming language.

In this C++ program, x0 & x1 are two initial guess values, e is tolerable error and f(x) is actual non-linear function whose root is being obtained using secant line method.

C++ Source Code: Secant Method


/* Program: Finding real roots of nonlinear
   equation using Secant Method
   Author: CodeSansar
   Date: November 18, 2018 */

#include<iostream>
#include<iomanip>
#include<math.h>
#include<stdlib.h>

/* Defining equation to be solved.
   Change this equation to solve another problem. */
#define    f(x)    x*x*x - 2*x - 5

using namespace std;

int main()
{
	 float x0, x1, x2, f0, f1, f2, e;
	 int step = 1, N;
	 
	 /* Setting precision and writing floating point values in fixed-point notation. */
   cout<< setprecision(6)<< fixed;

	 /* Inputs */
	 cout<<"Enter first guess: ";
	 cin>>x0;
	 cout<<"Enter second guess: ";
	 cin>>x1;
	 cout<<"Enter tolerable error: ";
	 cin>>e;
	 cout<<"Enter maximum iteration: ";
	 cin>>N;

	 /* Implementing Secant Method */
     cout<< endl<<"**************"<< endl;
	 cout<<"Secant Method"<< endl;
	 cout<<"**************"<< endl;
	 do
	 {
		  f0 = f(x0);
		  f1 = f(x1);
		  if(f0 == f1)
		  {
			   cout<<"Mathematical Error.";
			   exit(0);
		  }

		  x2 = x1 - (x1 - x0) * f1/(f1-f0);
		  f2 = f(x2);

		  cout<<"Iteration-"<< step<<":\t x2 = "<< setw(10)<< x2<<" and f(x2) = "<< setw(10)<< f(x2)<< endl;

		  x0 = x1;
		  f0 = f1;
		  x1 = x2;
		  f1 = f2;

		  step = step + 1;

		  if(step > N)
		  {
			   cout<<"Not Convergent.";
			   exit(0);
		  }
	 }while(fabs(f2)>e);

	 cout<< endl<<"Root is: "<< x2;

	 return 0;
}

C++ Program Output: Secant Method

Enter first guess: 0
Enter second guess: 1
Enter tolerable error: 0.000001
Enter maximum iteration: 10

**************
Secant Method
**************
Iteration-1:     x2 =  -5.000000 and f(x2) = -120.000000
Iteration-2:     x2 =   1.315789 and f(x2) =  -5.353550
Iteration-3:     x2 =   1.610713 and f(x2) =  -4.042600
Iteration-4:     x2 =   2.520173 and f(x2) =   5.965955
Iteration-5:     x2 =   1.978057 and f(x2) =  -1.216554
Iteration-6:     x2 =   2.069879 and f(x2) =  -0.271572
Iteration-7:     x2 =   2.096267 and f(x2) =   0.019166
Iteration-8:     x2 =   2.094527 and f(x2) =  -0.000268
Iteration-9:     x2 =   2.094552 and f(x2) =   0.000001

Root is: 2.094552