Find the root of an equation using Newton Raphson method in C++

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

Newton Raphson method: it is an algorithm that is used for finding the root of an equation. It starts its iterative process with an initial guess as an initial assumption for the root of function f(x) equal to zero. At each stage, it tries to approximate the value of root of a function by substituting the new value of root.

Algorithm:

  1. Initialize initial guess(X2) and desired accuracy(e).
  2. assign X2 to X1.
  3. Calculate X2 using formula => X2 = X1 – f(x1) / f ‘(x1)
  4. Repeat step 2-3 as long as |X2 – X1| is greater than desired accuracy(e).
  5. You will get the root of an equation in X2.

Program to find the root of an equation using the Newton Raphson method in C++

#include<iostream>
/* cmath header file is included for pow & fabs functions */
#include<cmath>
using namespace std;

double func(double );
double first_derivative(double );
void newton_raphson(double ,double );

int main()
{
    double x2,e;
   
    cout<<"Enter the initial guess: "; 
    cin>>x2;
    
    cout<<"Enter desired accuracy: ";
    cin>>e;

  newton_raphson(x2,e);
    
    return 0;
}

double func(double x)
{
  /* write the equation whose root you want to find. Here, we are using equation x^3 + x - 1 */
    double res=pow(x,3) + x - 1; 
    return res; 
}

double first_derivative(double x)
{
  /* In this function, we have to return the first derivative of our equation which will be 3*x^2 + 1 */
    return (3 * pow(x,2) + 1);  
}

void newton_raphson(double x2, double e) 
{ 
    double x1;
    
    do
    { 
    	x1=x2;
    	
    	/* Xi+1 = Xi - f(x) / f'(x) */
        x2 = x1 - func(x1)/first_derivative(x1); 
        
    }while(fabs(x2-x1) >= e);
    /* Stop the loop when |Xi+1 - Xi| becomes less than the desired accuracy(e) */
       
  cout<<"\nThe root of an equation is "<<x2;
}

Input/Output:

Enter the initial guess: 2
Enter desired accuracy: 0.001

The root of an equation is 0.682328

You may also learn:




  1. Secant Method to find the root of an equation in C++
  2. Add watermark to an image in C++


Leave a Reply

Your email address will not be published. Required fields are marked *