mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
commit
0577096360
36
math/sqrt_double.cpp
Normal file
36
math/sqrt_double.cpp
Normal file
@ -0,0 +1,36 @@
|
||||
#include <iostream>
|
||||
#include <cassert>
|
||||
|
||||
/* Calculate the square root of any
|
||||
number in O(logn) time,
|
||||
with precision fixed */
|
||||
|
||||
double Sqrt(double x) {
|
||||
double l = 0, r = x;
|
||||
/* Epsilon is the precision.
|
||||
A great precision is
|
||||
between 1e-7 and 1e-12.
|
||||
double epsilon = 1e-12;
|
||||
*/
|
||||
double epsilon = 1e-12;
|
||||
while ( l <= r ) {
|
||||
double mid = (l + r) / 2;
|
||||
if ( mid * mid > x ) {
|
||||
r = mid;
|
||||
} else {
|
||||
if ( x - mid * mid < epsilon ) {
|
||||
return mid;
|
||||
}
|
||||
l = mid;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
int main() {
|
||||
double n{};
|
||||
std::cin >> n;
|
||||
assert(n >= 0);
|
||||
// Change this line for a better precision
|
||||
std::cout.precision(12);
|
||||
std::cout << std::fixed << Sqrt(n);
|
||||
}
|
Loading…
Reference in New Issue
Block a user