mysqrt.cxx 877 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #include "mysqrt.h"
  2. #include <iostream>
  3. namespace mathfunctions {
  4. namespace detail {
  5. // a hack square root calculation using simple operations
  6. double mysqrt(double x)
  7. {
  8. if (x <= 0) {
  9. return 0;
  10. }
  11. // TODO 5: If both HAVE_LOG and HAVE_EXP are defined, use the following:
  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, use the existing logic.
  16. // Hint: Don't forget the #endif before returning the result!
  17. double result = x;
  18. // do ten iterations
  19. for (int i = 0; i < 10; ++i) {
  20. if (result <= 0) {
  21. result = 0.1;
  22. }
  23. double delta = x - (result * result);
  24. result = result + 0.5 * delta / result;
  25. std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
  26. }
  27. return result;
  28. }
  29. }
  30. }