The Wayback Machine - https://web.archive.org/web/20241030120416/https://www.geeksforgeeks.org/program-for-newton-raphson-method/
Open In App

Program for Newton Raphson Method

Last Updated : 02 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a function f(x) on floating number x and an initial guess for root, find root of function in interval. Here f(x) represents algebraic or transcendental equation. 
For simplicity, we have assumed that derivative of function is also provided as input.
Example:

Input: A function of x (for example x3 – x2 + 2),
       derivative function of x (3x2 – 2x for above example)
       and an initial guess x0 = -20
Output: The value of root is : -1.00
        OR any other value close to root.

We have discussed below methods to find root in set 1 and set 2 
Set 1: The Bisection Method 
Set 2: The Method Of False Position
Comparison with above two methods: 
 

  1. In previous methods, we were given an interval. Here we are required an initial guess value of root.
  2. The previous two methods are guaranteed to converge, Newton Raphson may not converge in some cases.
  3. Newton Raphson method requires derivative. Some functions may be difficult to 
    impossible to differentiate.
  4. For many problems, Newton Raphson method converges faster than the above two methods.
  5. Also, it can identify repeated roots, since it does not look for changes in the sign of f(x) explicitly

The formula: 
Starting from initial guess x1, the Newton Raphson method uses below formula to find next value of x, i.e., xn+1 from previous value xn. 
 

newtonraphsonformula

Advantages of Newton Raphson Method:

  • It is best method to solve the non-linear equations.
  • It can also be used to solve the system of non-linear equations, non-linear differential and non-linear integral equations.
  • The order of convergence is quadric i.e. of second order which makes this method fast as compared to other methods.
  • It is very easy to implement on computer.

Disadvantages of Newton Raphson Method:

  • This method becomes complicated if the derivative of the function f(x) is not simple.
  • This method requires a great and sensitive attention regarding the choice of its approximation.
  • In each iteration, we have to evaluate two quantities f(x) and f'(x) for some x.

Algorithm: 
Input: initial x, func(x), derivFunc(x) 
Output: Root of Func() 
 

  1. Compute values of func(x) and derivFunc(x) for given initial x
  2. Compute h: h = func(x) / derivFunc(x)
  3. While h is greater than allowed error ? 
    1. h = func(x) / derivFunc(x)
    2. x = x – h

Below is the implementation of above algorithm. 
 

C++




// C++ program for implementation of Newton Raphson Method for
// solving equations
#include<bits/stdc++.h>
#define EPSILON 0.001
using namespace std;
 
// An example function whose solution is determined using
// Bisection Method. The function is x^3 - x^2  + 2
double func(double x)
{
    return x*x*x - x*x + 2;
}
 
// Derivative of the above function which is 3*x^x - 2*x
double derivFunc(double x)
{
    return 3*x*x - 2*x;
}
 
// Function to find the root
void newtonRaphson(double x)
{
    double h = func(x) / derivFunc(x);
    while (abs(h) >= EPSILON)
    {
        h = func(x)/derivFunc(x);
  
        // x(i+1) = x(i) - f(x) / f'(x) 
        x = x - h;
    }
 
    cout << "The value of the root is : " << x;
}
 
// Driver program to test above
int main()
{
    double x0 = -20; // Initial values assumed
    newtonRaphson(x0);
    return 0;
}


Java




// Java program for implementation of
// Newton Raphson Method for solving
// equations
class GFG {
     
    static final double EPSILON = 0.001;
     
    // An example function whose solution
    // is determined using Bisection Method.
    // The function is x^3 - x^2 + 2
    static double func(double x)
    {
        return x * x * x - x * x + 2;
    }
     
    // Derivative of the above function
    // which is 3*x^x - 2*x
    static double derivFunc(double x)
    {
        return 3 * x * x - 2 * x;
    }
     
    // Function to find the root
    static void newtonRaphson(double x)
    {
        double h = func(x) / derivFunc(x);
        while (Math.abs(h) >= EPSILON)
        {
            h = func(x) / derivFunc(x);
     
            // x(i+1) = x(i) - f(x) / f'(x)
            x = x - h;
        }
     
        System.out.print("The value of the"
                + " root is : "
                + Math.round(x * 100.0) / 100.0);
    }
     
    // Driver code
    public static void main (String[] args)
    {
         
        // Initial values assumed
        double x0 = -20;
        newtonRaphson(x0);
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python3 code for implementation of Newton
# Raphson Method for solving equations
 
# An example function whose solution
# is determined using Bisection Method.
# The function is x^3 - x^2 + 2
def func( x ):
    return x * x * x - x * x + 2
 
# Derivative of the above function
# which is 3*x^x - 2*x
def derivFunc( x ):
    return 3 * x * x - 2 * x
 
# Function to find the root
def newtonRaphson( x ):
    h = func(x) / derivFunc(x)
    while abs(h) >= 0.0001:
        h = func(x)/derivFunc(x)
         
        # x(i+1) = x(i) - f(x) / f'(x)
        x = x - h
     
    print("The value of the root is : ",
                             "%.4f"% x)
 
# Driver program to test above
x0 = -20 # Initial values assumed
newtonRaphson(x0)
 
# This code is contributed by "Sharad_Bhardwaj"


C#




// C# program for implementation of
// Newton Raphson Method for solving
// equations
using System;
class GFG {
     
    static double EPSILON = 0.001;
     
    // An example function whose solution
    // is determined using Bisection Method.
    // The function is x^3 - x^2 + 2
    static double func(double x)
    {
        return x * x * x - x * x + 2;
    }
     
    // Derivative of the above function
    // which is 3*x^x - 2*x
    static double derivFunc(double x)
    {
        return 3 * x * x - 2 * x;
    }
     
    // Function to find the root
    static void newtonRaphson(double x)
    {
        double h = func(x) / derivFunc(x);
        while (Math.Abs(h) >= EPSILON)
        {
            h = func(x) / derivFunc(x);
     
            // x(i+1) = x(i) - f(x) / f'(x)
            x = x - h;
        }
     
        Console.Write("The value of the"
                    + " root is : "
                    + Math.Round(x * 100.0) / 100.0);
    }
     
    // Driver code
    public static void Main ()
    {
         
        // Initial values assumed
        double x0 = -20;
        newtonRaphson(x0);
    }
}
 
// This code is contributed by nitin mittal


PHP




<?php
// PHP program for implementation
// of Newton Raphson Method for
// solving equations
$EPSILON = 0.001;
 
// An example function whose
// solution is determined
// using Bisection Method.
// The function is x^3 - x^2 + 2
function func($x)
{
    return $x * $x * $x -
           $x * $x + 2;
}
 
// Derivative of the above
// function which is 3*x^x - 2*x
function derivFunc($x)
{
    return 3 * $x *
               $x - 2 * $x;
}
 
// Function to
// find the root
function newtonRaphson($x)
{
    global $EPSILON;
    $h = func($x) / derivFunc($x);
    while (abs($h) >= $EPSILON)
    {
        $h = func($x) / derivFunc($x);
 
        // x(i+1) = x(i) -
        // f(x) / f'(x)
        $x = $x - $h;
    }
 
    echo "The value of the ".
           "root is : " , $x;
}
 
// Driver Code
$x0 = -20; // Initial values assumed
newtonRaphson($x0);
 
// This code is contributed by ajit
?>


Javascript




<script>
 
// JavaScript program for implementation of
// Newton Raphson Method for solving
// equations
 
    let EPSILON = 0.001;
       
    // An example function whose solution
    // is determined using Bisection Method.
    // The function is x^3 - x^2 + 2
    function func(x)
    {
        return x * x * x - x * x + 2;
    }
       
    // Derivative of the above function
    // which is 3*x^x - 2*x
    function derivFunc(x)
    {
        return 3 * x * x - 2 * x;
    }
       
    // Function to find the root
    function newtonRaphson(x)
    {
        let h = func(x) / derivFunc(x);
        while (Math.abs(h) >= EPSILON)
        {
            h = func(x) / derivFunc(x);
       
            // x(i+1) = x(i) - f(x) / f'(x)
            x = x - h;
        }
       
        document.write("The value of the"
                + " root is : "
                + Math.round(x * 100.0) / 100.0);
    }
 
 
// Driver program
 
        // Initial values assumed
        let x0 = -20;
        newtonRaphson(x0);
 
// This code is contributed by susmitakundugoaldanga.
</script>


Output: 

The value of root is : -1.00 

How does this work? 
The idea is to draw a line tangent to f(x) at point x1. The point where the tangent line crosses the x axis should be a better estimate of the root than x1. Call this point x2. Calculate f(x2), and draw a line tangent at x2. 
 

newtonRaphsonMethod

We know that slope of line from (x1, f(x1)) to (x2, 0) is f'(x1)) where f’ represents derivative of f. 
 

f'(x1) = (0 - f(x1)) / (x2 - x1) 

f'(x1) *  (x2 - x1) =  - f(x1)

x2 =  x1 - f(x1) / f'(x1) 

By finding this point 'x2', we move closer towards the root.
We have to keep on repeating the above step till we get really close to 
the root or we find it.

In general, 
xn+1 =  xn - f(xn) / f'(xn) 

Alternate Explanation using Taylor’s Series: 
 

Let x1 be the initial guess. 

We can write x2 as below:
  xn+1  = xn + h ------- (1)
Here h would be a small value that can be positive or negative.

According to Taylor's Series, 
ƒ(x) that is infinitely differentiable can be written as below
f(xn+1) = f(xn  + h) 
       = f(xn) + h*f'(xn) + ((h*h)/2!)*(f''(xn)) + ...

Since we are looking for root of function, f(xn+1) = 0

f(xn) + h*f'(xn) + ((h*h)/2!)*(f''(xn)) + ... = 0

Now since h is small, h*h would be very small. 
So if we ignore higher order terms, we get

f(xn) + h*f'(xn) = 0

Substituting this value of h = xn+1 - xn from equation (1) we get, 
f(xn) + (xn+1  - xn)*f'(xn) = 0

xn+1 =  xn - f(xn) / f'(xn)  

Notes: 
 

  1. We generally used this method to improve the result obtained by either bisection method or method of false position.
  2. Babylonian method for square root is derived from the Newton-Raphson method.

References: 
Introductory Methods of Numerical Analysis by S.S. Sastry 
https://en.wikipedia.org/wiki/Newton’s_method 
http://www.cae.tntech.edu/Members/renfro/me2000/lectures/2004-09-07_handouts.pdf/at_download/file

 



Similar Reads

Find root of a number using Newton's method
Given an integer N and a tolerance level L, the task is to find the square root of that number using Newton's Method.Examples: Input: N = 16, L = 0.0001 Output: 4 42 = 16Input: N = 327, L = 0.00001 Output: 18.0831 Newton's Method: Let N be any number then the square root of N can be given by the formula: root = 0.5 * (X + (N / X)) where X is any gu
7 min read
Newton's Divided Difference Interpolation Formula
Interpolation is an estimation of a value within two known values in a sequence of values. Newton's divided difference interpolation formula is an interpolation technique used when the interval difference is not same for all sequence of values. Suppose f(x0), f(x1), f(x2).........f(xn) be the (n+1) values of the function y=f(x) corresponding to the
11 min read
Newton Forward And Backward Interpolation
Interpolation is the technique of estimating the value of a function for any intermediate value of the independent variable, while the process of computing the value of the function outside the given range is called extrapolation. Forward Differences: The differences y1 – y0, y2 – y1, y3 – y2, ......, yn – yn–1 when denoted by dy0, dy1, dy2, ......
15+ min read
Difference between Gauss Elimination Method and Gauss Jordan Method | Numerical Method
Gauss Elimination MethodGauss Elimination Method is one of the most widely used methods. This method is a systematic process of eliminating unknowns from the linear equations. This method is divided into two linear equations: Triangularization MethodBack Substitution MethodSteps Of the Gauss Elimination MethodConsider a system of equations: a11X+a1
4 min read
Javascript Program for Program to cyclically rotate an array by one
Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Following are steps. 1) Store last element in a variable say x. 2) Shift all elements one position ahead. 3) Replace first element o
2 min read
C# Program to Implement the Same Method in Multiple Classes
C# is a general-purpose programming language it is used to create mobile apps, desktop apps, websites, and games. In C#, an object is a real-world entity. Or in other words, an object is a runtime entity that is created at runtime. It is an instance of a class. In this article, Implement the same method in Multiple Classes The implementation of the
3 min read
Program for Bisection Method
Given a function f(x) on floating number x and two numbers ‘a’ and ‘b’ such that f(a)*f(b) < 0 and f(x) is continuous in [a, b]. Here f(x) represents algebraic or transcendental equation. Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0). Example: Input: A function of x, for example x3 - x2 + 2. And two values:
8 min read
Program for Muller Method
Given a function f(x) on floating number x and three initial distinct guesses for root of the function, find the root of function. Here, f(x) can be an algebraic or transcendental function.Examples: Input : A function f(x) = x[Tex]^3[/Tex] + 2x[Tex]^2[/Tex] + 10x - 20 and three initial guesses - 0, 1 and 2 .Output : The value of the root is 1.3688
13 min read
Program to find root of an equations using secant method
The secant method is used to find the root of an equation f(x) = 0. It is started from two distinct estimates x1 and x2 for the root. It is an iterative procedure involving linear interpolation to a root. The iteration stops if the difference between two intermediate values is less than the convergence factor. Examples : Input : equation = x3 + x -
8 min read
Program for Gauss-Jordan Elimination Method
Prerequisite : Gaussian Elimination to Solve Linear Equations Introduction : The Gauss-Jordan method, also known as Gauss-Jordan elimination method is used to solve a system of linear equations and is a modified version of Gauss Elimination Method. It is similar and simpler than Gauss Elimination Method as we have to perform 2 different process in
13 min read
Program for Picard's iterative method | Computational Mathematics
The Picard’s method is an iterative method and is primarily used for approximating solutions to differential equations. This method of solving a differential equation approximately is one of successive approximation; that is, it is an iterative method in which the numerical results become more and more accurate, the more times it is used. The Picar
10 min read
Transportation Problem | Set 6 (MODI Method - UV Method)
There are two phases to solve the transportation problem. In the first phase, the initial basic feasible solution has to be found and the second phase involves optimization of the initial basic feasible solution that was obtained in the first phase. There are three methods for finding an initial basic feasible solution, NorthWest Corner MethodLeast
7 min read
Write a program to Delete a Tree
To delete a tree, we must traverse all the nodes of the tree and delete them one by one. So, which traversal we should use - inorder traversal, preorder traversal, or the postorder traversal? The answer is simple. We should use the postorder traversal because before deleting the parent node, we should delete its child nodes first.We can delete the
11 min read
Write a program to add two numbers in base 14
Asked by Anshya. Base 14: Decimal numbersBase 14 numbers0011223344556677889910A11B12C13D14D1 Below are the different ways to add base 14 numbers.Method 1 Thanks to Raj for suggesting this method. 1. Convert both i/p base 14 numbers to base 10. 2. Add numbers. 3. Convert the result back to base 14. Method 2 Just add the numbers in base 14 in the sam
15 min read
C Program to Sort an array of names or strings
Given an array of strings in which all characters are of the same case, write a C function to sort them alphabetically. The idea is to use qsort() in C and write a comparison function that uses strcmp() to compare two strings. C/C++ Code #include <stdio.h> #include <stdlib.h> #include <string.h> // Defining comparator function as
2 min read
Program for subtraction of matrices
The below program subtracts of two square matrices of size 4*4, we can change N for a different dimension. Implementation: C/C++ Code // C++ program for subtraction of matrices #include <bits/stdc++.h> using namespace std; #define N 4 // This function subtracts B[][] from A[][], and stores // the result in C[][] void subtract(int A[][N], int
7 min read
Program to find sum of series 1 + 1/2 + 1/3 + 1/4 + .. + 1/n
If inverse of a sequence follows rule of an A.P i.e, Arithmetic progression, then it is said to be in Harmonic Progression.In general, the terms in a harmonic progression can be denoted as : 1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) .... 1/(a + nd). As Nth term of AP is given as ( a + (n – 1)d) .Hence, Nth term of harmonic progression is reciprocal of
4 min read
C++ Program to remove spaces from a string
Given a string, remove all spaces from it. For example "g e e k" should be converted to "geek" and " g e " should be converted to "ge". The idea is to traverse the string from left to right and ignore spaces while traversing. We need to keep track of two indexes, one for the current character being red and the other for the current index in the out
2 min read
C Program for Red Black Tree Insertion
Following article is extension of article discussed here.In AVL tree insertion, we used rotation as a tool to do balancing after insertion caused imbalance. In Red-Black tree, we use two tools to do balancing. Recoloring Rotation We try recoloring first, if recoloring doesn't work, then we go for rotation. Following is detailed algorithm. The algor
6 min read
Remove comments from a given C/C++ program
Given a C/C++ program, remove comments from it. We strongly recommend to minimize your browser and try this yourself first. The idea is to maintain two flag variables, one to indicate that a single line comment is started, another to indicate that a multiline comment is started. When a flag is set, we look for the end of comment and ignore all char
3 min read
Program to print factors of a number in pairs
Given a number n, the task of the programmer is to print the factors of the number in such a way that they occur in pairs. A pair signifies that the product of the pair should result in the number itself. Examples: Input : 24Output : 1*24 2*12 3*8 4*6Input : 50Output : 1*50 2*25 5*10Recommended: Please try your approach on {IDE} first, before movin
7 min read
Program to calculate the number of odd days in given number of years
Given an integer N, the task is to find the number of odd days in the years from 1 to N. Odd Days: Number of odd days refer to those days that are left in a certain year(s) when it's days gets converted into weeks. Say, an ordinary year has 365 days, that is 52 weeks and one odd day. This means, out of the 365 days in an ordinary year, 364 days wil
7 min read
C++ Program to implement Symbol Table
Prerequisite: Symbol Table A Symbol table is a data structure used by the compiler, where each identifier in program's source code is stored along with information associated with it relating to its declaration. It stores identifier as well as it's associated attributes like scope, type, line-number of occurrence, etc. Symbol table can be implement
4 min read
Recursive program to print formula for GCD of n integers
Given a function gcd(a, b) to find GCD (Greatest Common Divisor) of two number. It is also known that GCD of three elements can be found by gcd(a, gcd(b, c)), similarly for four element it can find the GCD by gcd(a, gcd(b, gcd(c, d))). Given a positive integer n. The task is to print the formula to find the GCD of n integer using given gcd() functi
4 min read
Program to find sum of first n natural numbers
Given a number n, find the sum of the first natural numbers. Examples : Input: n = 3 Output: 6 Explanation: Note that 1 + 2 + 3 = 6 Input : 5 Output : 15 Explanation : Note that 1 + 2 + 3 + 4 + 5 = 15Program to Find the Sum of First N Natural Numbers A simple solution is to do the following. 1) Initialize : sum = 0 2) Run a loop from x = 1 to n and
10 min read
Program for diamond pattern with different layers
Given a number n and using 0-n numbers you have to print such a pattern.Examples: Input : n = 5 Output : 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 4 5 4 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 Input : n = 3 Output : 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 The idea here is to count the space in beginning o
10 min read
Program to find gravitational force between two objects
Introduction to Gravitational Force We know that gravity is universal. According to Newton's Law of Universal Gravitation, all objects attract each other with a force of gravitational attraction. According to this law, the force of gravitational attraction is directly dependent upon the masses of both objects and inversely proportional to the squar
4 min read
Program to check if N is an Icosikaioctagonal Number
Given an integer N, the task is to check if it is a icosikaioctagonal number or not. An icosikaioctagonal number is class of figurate number. It has 28 – sided polygon called icosikaioctagon. The N-th icosikaioctagonal number count’s the 28 number of dots and all other dots are surrounding with a common sharing corner and make a pattern. The first
4 min read
Program to find correlation coefficient
Given two array elements and we have to find the correlation coefficient between two arrays. The correlation coefficient is an equation that is used to determine the strength of the relation between two variables. The correlation coefficient is sometimes called as cross-correlation coefficient. The correlation coefficient always lies between -1 to
8 min read
Program to find slope of a line
Given two coordinates, find the slope of a straight line. Examples: Input : x1 = 4, y1 = 2, x2 = 2, y2 = 5 Output : Slope is -1.5 Approach: To calculate the slope of a line you need only two points from that line, (x1, y1) and (x2, y2). The equation used to calculate the slope from two points is: Below is the implementation of the above approach: C
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg