1
0

mysqrt.cxx 705 B

12345678910111213141516171819202122232425262728293031323334
  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. // use the table to help find an initial value
  14. double result = x;
  15. if (x >= 1 && x < 10) {
  16. result = sqrtTable[static_cast<int>(x)];
  17. }
  18. // do ten iterations
  19. for (int i = 0; i < 10; ++i) {
  20. if (result <= 0) {
  21. result = 0.1;
  22. }
  23. double delta = x - (result * result);
  24. result = result + 0.5 * delta / result;
  25. std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
  26. }
  27. return result;
  28. }