TheAlgorithms-C-Plus-Plus/math/sqrt_double.cpp

40 lines
830 B
C++
Raw Normal View History

#include <iostream>
#include <cassert>
2020-04-25 21:21:45 +08:00
/* Calculate the square root of any
number in O(logn) time,
with precision fixed */
2020-04-25 21:25:00 +08:00
double Sqrt(double x) {
2020-05-20 11:05:03 +08:00
if ( x > 0 && x < 1 ) {
return 1/Sqrt(1/x);
}
double l = 0, r = x;
2020-04-25 21:21:45 +08:00
/* Epsilon is the precision.
A great precision is
between 1e-7 and 1e-12.
double epsilon = 1e-12;
2020-04-25 21:21:45 +08:00
*/
2020-04-25 21:30:52 +08:00
double epsilon = 1e-12;
2020-04-25 21:28:31 +08:00
while ( l <= r ) {
2020-04-25 21:29:50 +08:00
double mid = (l + r) / 2;
2020-04-25 21:25:00 +08:00
if ( mid * mid > x ) {
r = mid;
2020-04-25 21:26:36 +08:00
} else {
2020-04-25 21:25:00 +08:00
if ( x - mid * mid < epsilon ) {
return mid;
}
l = mid;
}
}
return -1;
}
2020-04-25 21:25:00 +08:00
int main() {
double n{};
std::cin >> n;
assert(n >= 0);
2020-04-25 21:25:00 +08:00
// Change this line for a better precision
std::cout.precision(12);
std::cout << std::fixed << Sqrt(n);
}