mysqrt.cxx 786 B

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