mysqrt.cxx 807 B

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