mysqrt.cxx 738 B

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