mysqrt.cxx 786 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include <stdio.h>
  2. #include "MathFunctions.h"
  3. #include "TutorialConfig.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. {
  12. return 0;
  13. }
  14. double result;
  15. // if we have both log and exp then use them
  16. double delta;
  17. // use the table to help find an initial value
  18. result = x;
  19. if (x >= 1 && x < 10)
  20. {
  21. result = sqrtTable[static_cast<int>(x)];
  22. }
  23. // do ten iterations
  24. int i;
  25. for (i = 0; i < 10; ++i)
  26. {
  27. if (result <= 0)
  28. {
  29. result = 0.1;
  30. }
  31. delta = x - (result*result);
  32. result = result + 0.5*delta/result;
  33. fprintf(stdout,"Computing sqrt of %g to be %g\n",x,result);
  34. }
  35. return result;
  36. }