1#include <math.h>
2
3double sqrt(double x) {
4 if (x <= 0)
5 return 0; // if negative number throw an exception?
6 int exp = 0;
7 x = frexp(x, &exp); // extract binary exponent from x
8 if (exp & 1) { // we want exponent to be even
9 exp--;
10 x *= 2;
11 }
12 double y = (1+x)/2; // first approximation
13 double z = 0;
14 while (y != z) { // yes, we CAN compare doubles here!
15 z = y;
16 y = (y + x/y) / 2;
17 }
18 return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
19}
20
1double sqrt(double number)
2{
3 double error = 0.00001; //define the precision of your result
4 double s = number;
5
6 while ((s - number / s) > error) //loop until precision satisfied
7 {
8 s = (s + number / s) / 2;
9 }
10 return s;
11}
12
1 #include <iostream>
2 using namespace std;
3
4 double SqrtNumber(double num)
5 {
6 double lower_bound=0;
7 double upper_bound=num;
8 double temp=0; /* ek edited this line */
9
10 int nCount = 50;
11
12 while(nCount != 0)
13 {
14 temp=(lower_bound+upper_bound)/2;
15 if(temp*temp==num)
16 {
17 return temp;
18 }
19 else if(temp*temp > num)
20
21 {
22 upper_bound = temp;
23 }
24 else
25 {
26 lower_bound = temp;
27 }
28 nCount--;
29 }
30 return temp;
31 }
32
33 int main()
34 {
35 double num;
36 cout<<"Enter the number\n";
37 cin>>num;
38
39 if(num < 0)
40 {
41 cout<<"Error: Negative number!";
42 return 0;
43 }
44
45 cout<<"Square roots are: +"<<sqrtnum(num) and <<" and -"<<sqrtnum(num);
46 return 0;
47 }
48
1double SqrtNumber(double num)
2{
3 double lower_bound=0;
4 double upper_bound=num;
5 double temp=0;
6
7 while(fabs(num - (temp * temp)) > SOME_SMALL_VALUE)
8 {
9 temp = (lower_bound+upper_bound)/2;
10 if (temp*temp >= num)
11 {
12 upper_bound = temp;
13 }
14 else
15 {
16 lower_bound = temp;
17 }
18 }
19 return temp;
20 }
21