mysqrt.cxx 756 B

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