Imported Upstream version 3.25.0
[platform/upstream/cmake.git] / Help / guide / tutorial / Step8 / MathFunctions / mysqrt.cxx
1 #include <cmath>
2 #include <iostream>
3
4 #include "MathFunctions.h"
5
6 // a hack square root calculation using simple operations
7 double mysqrt(double x)
8 {
9   if (x <= 0) {
10     return 0;
11   }
12
13   // if we have both log and exp then use them
14 #if defined(HAVE_LOG) && defined(HAVE_EXP)
15   double result = std::exp(std::log(x) * 0.5);
16   std::cout << "Computing sqrt of " << x << " to be " << result
17             << " using log and exp" << std::endl;
18 #else
19   double result = x;
20
21   // do ten iterations
22   for (int i = 0; i < 10; ++i) {
23     if (result <= 0) {
24       result = 0.1;
25     }
26     double delta = x - (result * result);
27     result = result + 0.5 * delta / result;
28     std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
29   }
30 #endif
31   return result;
32 }