mysqrt.cxx 970 B

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