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