TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
babylonian_method.cpp
Go to the documentation of this file.
1
12#include <cassert>
13#include <cmath>
14#include <iostream>
15
21namespace numerical_methods {
22
30double babylonian_method(double radicand) {
31 int i = 1;
32
33 while (i * i <= radicand) {
34 i++;
35 }
36
37 i--;
38
39 double x0 = i;
40 double x1 =
41 (radicand / x0 + x0) / 2;
42 double temp = NAN;
43
44 while (std::max(x0, x1) - std::min(x0, x1) < 0.0001) {
45 temp = (radicand / x1 + x1) / 2;
46 x0 = x1;
47 x1 = temp;
48 }
49
50 return x1;
51}
52
53} // namespace numerical_methods
54
62static void test() {
63 /* descriptions of the following test */
64
65 auto testcase1 = 125348;
66 auto testcase2 = 752080;
67
68 auto real_output1 = 354.045194855;
69 auto real_output2 = 867.225460881;
70
71 auto test_result1 = numerical_methods::babylonian_method(testcase1);
73 auto test_result2 = numerical_methods::babylonian_method(testcase2);
75
76 assert(std::max(test_result1, real_output1) -
77 std::min(test_result1, real_output1) <
78 0.0001);
80 assert(std::max(test_result2, real_output2) -
81 std::min(test_result2, real_output2) <
82 0.0001);
84
85 std::cout << "All tests have successfully passed!\n";
86}
87
96int main(int argc, char const *argv[]) {
97 test(); // run self-test implementations
98 // with 2 defined test cases
99 return 0;
100}
static void test()
Self-test implementations.
int main()
Main function.
double babylonian_method(double radicand)
Babylonian methods is an iterative function which returns square root of radicand.