File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments