A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://TheAlgorithms.github.io/C-Plus-Plus/da/d24/sqrt__double_8cpp.html below:

TheAlgorithms/C++: math/sqrt_double.cpp File Reference

Loading...

Searching...

No Matches

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>

Go to the source code of this file.

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

Definition in file sqrt_double.cpp.

◆ main()

main function

Definition at line 42 of file sqrt_double.cpp.

42 {

43 double n{};

44 std::cin >> n;

45 assert(n >= 0);

46

47 std::cout.precision(12);

48

std::cout << std::fixed <<

Sqrt

(n);

49}

◆ Sqrt()

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

Definition at line 16 of file sqrt_double.cpp.

16 {

17 if (a > 0 && a < 1) {

18 return

1 /

Sqrt

(1 / a);

19 }

21

22

23

24

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 }

36 }

37 }

38 return -1;

39}

double l(double x)

Another test function.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4