Update sqrt_double.cpp

This commit is contained in:
DarkWarrior703 2020-04-25 16:25:00 +03:00 committed by GitHub
parent 878dc0bf6c
commit d4ab125657
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5,35 +5,30 @@
number in O(logn) time, number in O(logn) time,
with precision fixed */ with precision fixed */
double Sqrt(double x) double Sqrt(double x) {
{
double l = 0, r = x; double l = 0, r = x;
/* Epsilon is the precision. /* Epsilon is the precision.
A great precision is A great precision is
between 1e-7 and 1e-12. between 1e-7 and 1e-12.
double epsilon = 1e-12; double epsilon = 1e-12;
*/ */
while( l <= r ) while ( l <= r) {
{
double mid = (l + r) / 2; double mid = (l + r) / 2;
if( mid * mid > x ) if ( mid * mid > x ) {
{
r = mid; r = mid;
} }
else else {
{ if ( x - mid * mid < epsilon ) {
if( x - mid * mid < epsilon )
{
return mid; return mid;
} }
l = mid; l = mid;
} }
} }
return -1; return -1;
} }
int main() int main() {
{
double n{}; double n{};
std::cin >> n; std::cin >> n;
assert(n >= 0); assert(n >= 0);