mysqrt.cxx 1019 B

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