mysqrt.cxx 765 B

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