mysqrt.cxx 998 B

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