mysqrt.cxx 765 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #include "MathFunctions.h"
  2. #include "TutorialConfig.h"
  3. #include <stdio.h>
  4. // include the generated table
  5. #include "Table.h"
  6. #include <math.h>
  7. // a hack square root calculation using simple operations
  8. double mysqrt(double x)
  9. {
  10. if (x <= 0) {
  11. return 0;
  12. }
  13. double result;
  14. // if we have both log and exp then use them
  15. double delta;
  16. // use the table to help find an initial value
  17. result = x;
  18. if (x >= 1 && x < 10) {
  19. result = sqrtTable[static_cast<int>(x)];
  20. }
  21. // do ten iterations
  22. int i;
  23. for (i = 0; i < 10; ++i) {
  24. if (result <= 0) {
  25. result = 0.1;
  26. }
  27. delta = x - (result * result);
  28. result = result + 0.5 * delta / result;
  29. fprintf(stdout, "Computing sqrt of %g to be %g\n", x, result);
  30. }
  31. return result;
  32. }