Theory
Newton Raphson Method (NR-method) is an open-end method that uses only one initial guess based on a linear approximation of a function using a tangent to a curve.
Consider a graph f(x) as shown in the figure. Let us assume that x1 is an approximate root of f(x). Now draw a tangent on the curve f(x) at x = x1. The point of intersection of this tangent with the x-axis gives the second approximation.
From figure (1),
tanθ = f(x1) / (x1 – x2)
tanθ = f'(x1)
where,
f'(x1) is the slope of f(x) at x = x1
On solving
x2 = x1 – f(x1) / f'(x2)
Then the next approximation will be
x3 = x2 – f(x2) / f'(x2)
In general,
xn+1 = xn – f(xn) / f'(xn)

Algorithm
- Start
- Define function f(x), and its derivative g(x) and error E
- Read initial guess x0
- Calcualte x1 = x0 – f(x0) / g(x0)
- If |x1 – x0| <= E, print root x1
- else, goto step 4
- Stop
Source Code
#include<iostream> #include<math.h> #define f(x) (x*x - 4*x - 10) #define g(x) (2*x - 4) // derivative of f(x) #define E 0.0001 using namespace std; int main() { float x1, x2, f1, f2, g1; cout<<"Enter the initial values"<<endl; cin>>x1; do { f1 = f(x1); g1 = g(x1); x2 = x1 - (f1/g1); x1 = x2; f2 = f(x2); }while(f2 > E); cout<<"Root is "<<x2; return 0; }
Output
Enter the initial values
4
Root is 5.74166