mysqrt.cxx 775 B

123456789101112131415161718192021222324252627282930313233
  1. #include "MathFunctions.h"
  2. #include "TutorialConfig.h"
  3. #include <iostream>
  4. #include <cmath>
  5. // a hack square root calculation using simple operations
  6. double mysqrt(double x)
  7. {
  8. if (x <= 0) {
  9. return 0;
  10. }
  11. // if we have both log and exp then use them
  12. #if defined(HAVE_LOG) && defined(HAVE_EXP)
  13. double result = exp(log(x) * 0.5);
  14. std::cout << "Computing sqrt of " << x << " to be " << result << " using log"
  15. << std::endl;
  16. #else
  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. #endif
  28. return result;
  29. }