Skip to content

Commit 41cd98c

Browse files
authored
Program to find the square root of a number
1 parent 1446945 commit 41cd98c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

SquareRoot.c

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/* Program to find the square root of a number
2+
* - the current implementation uses the Newton-Raphson method
3+
* - mathematical explanation can be found online, and requires basic calculus knowledge
4+
*/
5+
6+
#include <stdio.h>
7+
#include <math.h> // for 'fabs' - returns unsigned absolute value
8+
9+
const double MAX_ERROR = 1e-7; // equivalent to 10^-7 -> accurate upto 7 decimal places
10+
// can be set according to need or even taken in as input
11+
12+
double squareRoot(int x)
13+
{
14+
double r = 1; // initial guess for the root
15+
while (fabs(r*r - x) > MAX_ERROR)
16+
{
17+
r = (r + x/r) / 2;
18+
// value of 'r' moves closer and closer to the actual root value
19+
}
20+
21+
return r;
22+
}
23+
24+
int main()
25+
{
26+
// the number for which we expect to compute the root
27+
int num;
28+
scanf("%d", &num);
29+
30+
printf("%lf \n", squareRoot(num));
31+
32+
return 0;
33+
}

0 commit comments

Comments
 (0)