mysqrt.cxx 747 B

123456789101112131415161718192021222324252627282930313233343536
  1. #include "MathFunctions.h"
  2. #include "TutorialConfig.h"
  3. #include <stdio.h>
  4. #include <math.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. double result;
  12. // if we have both log and exp then use them
  13. #if defined(HAVE_LOG) && defined(HAVE_EXP)
  14. result = exp(log(x) * 0.5);
  15. fprintf(stdout, "Computing sqrt of %g to be %g using log\n", x, result);
  16. #else
  17. double delta;
  18. result = x;
  19. // do ten iterations
  20. int i;
  21. for (i = 0; i < 10; ++i) {
  22. if (result <= 0) {
  23. result = 0.1;
  24. }
  25. delta = x - (result * result);
  26. result = result + 0.5 * delta / result;
  27. fprintf(stdout, "Computing sqrt of %g to be %g\n", x, result);
  28. }
  29. #endif
  30. return result;
  31. }