8153f18bed9fb3d515afd77584fcf3238fa3879e
[platform/upstream/cmake.git] / Help / guide / tutorial / Step10 / MathFunctions / mysqrt.cxx
1 #include <iostream>
2
3 #include "MathFunctions.h"
4
5 // include the generated table
6 #include "Table.h"
7
8 namespace mathfunctions {
9 namespace detail {
10 // a hack square root calculation using simple operations
11 double mysqrt(double x)
12 {
13   if (x <= 0) {
14     return 0;
15   }
16
17   // use the table to help find an initial value
18   double result = x;
19   if (x >= 1 && x < 10) {
20     std::cout << "Use the table to help find an initial value " << std::endl;
21     result = sqrtTable[static_cast<int>(x)];
22   }
23
24   // do ten iterations
25   for (int i = 0; i < 10; ++i) {
26     if (result <= 0) {
27       result = 0.1;
28     }
29     double delta = x - (result * result);
30     result = result + 0.5 * delta / result;
31     std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
32   }
33
34   return result;
35 }
36 }
37 }