mysqrt.cxx 860 B

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