# Successive approximation in C++

In this tutorial, we will learn **how to find out the root of an equation using the successive approximation method in C++. **Before proceeding further let’s first understand what is a successive approximation.

**Successive approximation: **It is an iterative method that is used for finding the root of an equation. It starts its iterative process with an initial approximation. At each stage, it tries to approximate the root of an equation in such a way that the inconsistency between the newest estimated root and the original root is systematically reduced.

It has huge importance in mathematics. it is widely used in many fixed point theories.

**Algorithm: Successive approximation**

- Initialize x0(initial approximation) and xn.
- assign x0 to xn and increment x0.
- repeat step 2 until f(x0)*f(xn) is positive.
- assign xn to x0.
- assign the result of the g(x0) to xn.
- repeat steps 4-5 until |xn-x0| is greater than the accepted error.

## Program to find the root of an equation using the successive approximation method in C++

#include<iostream> /* cmath header file is included for cos() function */ #include<cmath> /* iomanip header file is included for setprecision() function */ #include<iomanip> using namespace std; double f(double x) { /* return the equation whose root is to be determined. Here, we have used equation: cos(x)-3x+5=0 */ return (double)cos(x)-3*x+5; } double g(double x) { /* In this function we have to return x. For cos(x)-3*x+5=0, value of x will be (cos(x)+5)/3. */ return (double)(cos(x)+5)/3; } int main() { double x0,xn=1; int iter=0; cout<<"Enter the initial approximation: "; cin>>x0; cout<<"\nIteration x0 xn\n"; while(f(x0)*f(xn)>0) { xn=x0; x0++; } /* 0.000001 is the accepted error */ while(fabs(xn-x0)>0.000001) { x0=xn; xn=g(x0); iter++; cout<<" "<<iter<<" "<<x0<<" "<<setprecision(6)<<xn<<"\n"; } cout<<"\n\nThe root of the equation cos(x)-3x+5=0 is "<<xn; return 0; }

**Input/Output:**

Enter the initial approximation: 0 Iteration x0 xn 1 1 1.84677 2 1.84677 1.57584 3 1.57584 1.66499 4 1.66499 1.63532 5 1.63532 1.64517 6 1.64517 1.6419 7 1.6419 1.64299 8 1.64299 1.64262 9 1.64262 1.64274 10 1.64274 1.6427 11 1.6427 1.64272 12 1.64272 1.64271 13 1.64271 1.64271 14 1.64271 1.64271 The root of the equation cos(x)-3x+5=0 is 1.64271

**You may also learn:**

## Leave a Reply