From a23baf9db11959f4d9f117fb7c7be52b33cd9416 Mon Sep 17 00:00:00 2001 From: DarkWarrior703 <56077342+DarkWarrior703@users.noreply.github.com> Date: Fri, 24 Apr 2020 20:54:32 +0300 Subject: [PATCH] Create sqrt_double Calculates the sqrt of every number in O(logn) with fixed precision. --- math/sqrt_double | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 math/sqrt_double diff --git a/math/sqrt_double b/math/sqrt_double new file mode 100644 index 000000000..ee0c723ef --- /dev/null +++ b/math/sqrt_double @@ -0,0 +1,32 @@ +#include +#include + +/* 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; + 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); +}