In this article, we will discuss the Secant Method in C++ with its algorithm and examples.
What is the Secant Method?
A numerical method for determining a nonlinear equation's root is the secant method . It is an iterative process that begins with two preliminary estimates, x1 and x2 , which do not always include the root. After that, the method linearly interpolates between the two predictions to repeatedly approximate the root.
The secant technique iterates indefinitely, or until a maximum number of iterations is reached, or until the difference between subsequent approximations drops below the specified tolerance level.
Algorithm:
Step 1: Choose i=1
Step 2: Start with the initial guesses, x i-1 and x i
Step 3: Use the formula
Step 4: Find Absolute Error, |Ea|= |(X i+1 -Xi)/X i+1 |*100
Check if |Ea| <= Es (Prescribed tolerance)
If true then stop
Else go to step 2 with estimate X i+1 , X i
Program 1:
Let us take an example to illustrate the Secant Method in C++.
#include <iostream>
#include <cmath>
using namespace std;
// Function for which we are finding the root
double f(double x) {
return x * x - 4; // Example function: f(x) = x^2 - 4
}
// Secant method function
double secantMethod(double x0, double x1, double tol, int maxIter) {
double x2, fx0, fx1, fx2, error = tol + 1;
int iter = 0;
while (error > tol && iter < maxIter) {
fx0 = f(x0);
fx1 = f(x1);
x2 = x1 - ((fx1 * (x1 - x0)) / (fx1 - fx0));
fx2 = f(x2);
error = abs(x2 - x1);
x0 = x1;
x1 = x2;
iter++;
cout << "Iteration " << iter << ": x = " << x2 << ", f(x) = " << fx2 << ", error = " << error << endl;
}
return x2;
}
int main() {
double x0 = 1, x1 = 3, tol = 0.0001;
int maxIter = 100;
cout << "Initial guess x0 = " << x0 << ", x1 = " << x1 << endl;
double root = secantMethod(x0, x1, tol, maxIter);
cout << "Root found at x = " << root << endl;
return 0;
}
Output:
Program 2:
Let us take another example to illustrate the Secant Method in C++.
#include<iostream>
#include<cmath>
//for specifying format
#include<bits/stdc++.h>
using namespace std;
//prespecified error tolerance
#define Es 0.0001
float F(float x){
float res;
res=(x*x)-(2*x)-5;
return res;
}
int main(){
float x0,x1,x2,x2old,f0,f1,f2;
int itr=1;
float Ea;
cout<<"Enter the initial guesses (x0,x1): ";
cin>>x0>>x1;
cout<<"Itr No.\tx0\tx1\tf0\tf1\tx2\t f2\tEa\n";
cout<<"----------------------------------------------------------------------------\n";
while (1){
f0=F(x0);
f1=F(x1);
x2=x1-(f1*(x1-x0)/(f1-f0));
f2=F(x2);
//finding absolute error
Ea=fabs((x2-x1)/x2);
cout<<fixed<<setprecision(3);
cout<<itr<<"\t"<<x0<<"\t"<<x1<<"\t"<<f0<<"\t"<<f1<<"\t"<<x2<<"\t"<<f2<<"\t"<<Ea<<"\n";
x0=x1;
x1=x2;
itr++;
if(Ea<=Es)
break;
}
cout<<"Approximate root (x2) is: "<<x2;
return 0;
}
Output: