mysqrt.cxx 775 Bytes
Newer Older
1 2
#include "MathFunctions.h"
#include "TutorialConfig.h"
3
#include <iostream>
4

5
#include <cmath>
6 7 8 9

// a hack square root calculation using simple operations
double mysqrt(double x)
{
10
  if (x <= 0) {
11
    return 0;
12
  }
13

14
  // if we have both log and exp then use them
15 16 17 18 19 20
#if defined(HAVE_LOG) && defined(HAVE_EXP)
  double result = exp(log(x) * 0.5);
  std::cout << "Computing sqrt of " << x << " to be " << result << " using log"
            << std::endl;
#else
  double result = x;
21 22

  // do ten iterations
23
  for (int i = 0; i < 10; ++i) {
24
    if (result <= 0) {
25 26
      result = 0.1;
    }
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
#endif
32 33
  return result;
}