Newton Raphson method program in C++

In this program, we will implement the Newton-Raphson method for finding a good approximation root of an equation. The Newton-Raphson method is also known as Newton Method.

Formula: Xn+1=Xn - f(Xn) / f'(Xn)

where Xn is the initial root value.

for example, if you want to find the root of f(x) equation x2 - 4 = 0. you will get x value 2.

This is a simple example, but you can solve the root of a complex equation easily with the help of Newton's method.

Program to find Newton-Raphson method


#include <iostream>
#include <math.h>
using namespace std;

/*equation f(x) */
float f(float x) {
  /* change the equation for solving another problem */
  return pow(x, 2) - 6;
}

/* derivative of equation i.e f'(x) */
float derivative(float x) {
  /* write the derivative of your equation */
  return 2 * x;
}

int main() {
  float x;
  int n, i;

  cout << "Enter initial guess value: ";
  cin >> x;

  cout <<"Enter number of iterations: ";
  cin >> n;
  
  for (i = 1; i <= n; i++) 
  {
    if (derivative(x) == 0) {
      // f'(x) should not be 0
      printf("Division by Zero is not allowed.");
      exit(0);
    }

    //Newton Raphson formula
    x = x - f(x) / derivative(x);

    cout <<"Iteration "<<i<< " and value "<<x<< endl;
  }
  
   cout <<"\n approximate root: "<<x<< endl;
  return 0;
}
output
Enter initial guess value: 5
Enter number of iterations: 6
Iteration 1 and value 3.1
Iteration 2 and value 2.51774
Iteration 3 and value 2.45041
Iteration 4 and value 2.44949
Iteration 5 and value 2.44949
Iteration 6 and value 2.44949

 approximate root: 2.44949
Explanation

In the above program, you will take an initial value from the user i.e x, and a number of iterations say n.

now iterate the loop from 1 to n. inside the loop find a derivative and check derivative is zero or not. if zero then exit the loop. if you get derivative zero then you will not be able to find the root of an equation.

Inside a loop, iterate the newton method and with each iteration, you will get a new approximate root value that is closer to your given equation root value.

Note: if your initial value is closer to your root value and the number of iterations is larger then you will get a more accurate value.