Skip to content

Commit ea90ced

Browse files
committed
Newton Raphson Algorithm for square root
1 parent 9377f65 commit ea90ced

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

Diff for: NewtonRaphsonAlgo.cpp

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
//calculating the square root of a number using Newton Raphson method.
2+
3+
// what is Newton Raphson method?
4+
5+
/*
6+
It is a gradient based technique used to find root of a given number.
7+
according to this method,
8+
9+
Xn+1 = Xn - f(Xn)/f'(Xn) - (1) {where n is the nth term i.e 0,1,2,....}
10+
11+
12+
we know,
13+
X = (N)^1/r
14+
15+
where N is a number of which we want to find rth root (X).
16+
17+
above equation can be written as,
18+
X^r - N = 0
19+
=> f(X) = X^r - N = 0 - (a)
20+
=> f'(X) = r*X^(r-1) - (b)
21+
22+
now, putting nth term of equation (a) and (b) in equation (1)
23+
Xn+1 = Xn - (Xn^r - N) / r*Xn^(r-1)
24+
25+
taking L.C.M,
26+
Xn+1 = [ r*Xn^r - (Xn^r - N) ] / r*Xn^(r-1)
27+
28+
sovling further,
29+
30+
Xn+1 = [(r-1)Xn^r + N] / r*Xn^r-1 - (2)
31+
32+
This is the formula to get the rth root of a positive integer N, where X is our approximation number.
33+
34+
now, our aim is to get square root right, so, in equation (2) put r = 2.
35+
36+
Xn+1 = ( Xn^2 + N ) / 2 * Xn^2 [This is our equation which we are going to use to calculate square root of a number programatically]
37+
*/
38+
39+
#include<math.h>
40+
#include<stdlib.h>
41+
#include<iostream>
42+
using namespace std;
43+
44+
void squareRoot(int number){
45+
46+
double x, root;
47+
48+
x = number; // x is our approximation number(or Xn in equation (2))
49+
// i.e the number which we assume can be the square root of number
50+
// which we assume to be the number itself
51+
while(1){
52+
53+
root = (x + number/x)/2; // root is our Xn+1 th term (as in equation (2))
54+
if(abs(root - x) < 0.0001) // 0.0001 is our precision value an the loop is run until we get precision upto desired decimal places
55+
break;
56+
57+
x = root;
58+
}
59+
60+
cout<<root;
61+
}
62+
63+
int main(){
64+
system("cls");
65+
int n;
66+
67+
cout<<"enter a number: ";
68+
cin>>n;
69+
fflush(stdin);
70+
squareRoot(n);
71+
getchar();
72+
return 0;
73+
}

Diff for: NewtonRaphsonAlgo.exe

47.8 KB
Binary file not shown.

0 commit comments

Comments
 (0)