Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
sqrt_double.cpp File Reference

Calculate the square root of any positive real number in \(O(\log N)\) time, with precision fixed using bisection method of root-finding. More...

#include <cassert>
#include <iostream>
Include dependency graph for sqrt_double.cpp:

Functions

double Sqrt (double a)
 
int main ()
 

Detailed Description

Calculate the square root of any positive real number in \(O(\log N)\) time, with precision fixed using bisection method of root-finding.

See also
Can be implemented using faster and better algorithms like newton_raphson_method.cpp and false_position.cpp

Function Documentation

◆ main()

int main ( void )

main function

42 {
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}
T fixed(T... args)
double Sqrt(double a)
Definition sqrt_double.cpp:16
Here is the call graph for this function:

◆ Sqrt()

double Sqrt ( double a)

Bisection method implemented for the function \(x^2-a=0\) whose roots are \(\pm\sqrt{a}\) and only the positive root is returned.

16 {
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}
double l(double x)
Another test function.
Definition composite_simpson_rule.cpp:119
Here is the call graph for this function: