mysqrt.cxx 902 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #include "mysqrt.h"
  2. // TODO 4: 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. // TODO 5: If both HAVE_LOG and HAVE_EXP are defined, use the following:
  13. //// double result = std::exp(std::log(x) * 0.5);
  14. //// std::cout << "Computing sqrt of " << x << " to be " << result
  15. //// << " using log and exp" << std::endl;
  16. // else, use the existing logic.
  17. // Hint: Don't forget the #endif before returning the result!
  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. return result;
  29. }
  30. }
  31. }