TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
sqrt_double.cpp
Go to the documentation of this file.
1
10#include <cassert>
11#include <iostream>
12
16double Sqrt(double a) {
17 if (a > 0 && a < 1) {
18 return 1 / Sqrt(1 / a);
19 }
20 double l = 0, r = a;
21 /* Epsilon is the precision.
22 A great precision is
23 between 1e-7 and 1e-12.
24 double epsilon = 1e-12;
25 */
26 double epsilon = 1e-12;
27 while (l <= r) {
28 double mid = (l + r) / 2;
29 if (mid * mid > a) {
30 r = mid;
31 } else {
32 if (a - mid * mid < epsilon) {
33 return mid;
34 }
35 l = mid;
36 }
37 }
38 return -1;
39}
40
42int main() {
43 double n{};
44 std::cin >> n;
45 assert(n >= 0);
46 // Change this line for a better precision
47 std::cout.precision(12);
48 std::cout << std::fixed << Sqrt(n);
49}
double Sqrt(double a)
int main()