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