sqrt.c 759 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. sqrt returns the square root of its floating
  3. point argument. Newton's method.
  4. calls frexp
  5. */
  6. #include <math.h>
  7. #include <errno.h>
  8. #define _RESEARCH_SOURCE
  9. #include <float.h>
  10. double
  11. sqrt(double arg)
  12. {
  13. double x, temp;
  14. int exp, i;
  15. if(isInf(arg, 1))
  16. return arg;
  17. if(arg <= 0) {
  18. if(arg < 0)
  19. errno = EDOM;
  20. return 0;
  21. }
  22. x = frexp(arg, &exp);
  23. while(x < 0.5) {
  24. x *= 2;
  25. exp--;
  26. }
  27. /*
  28. * NOTE
  29. * this wont work on 1's comp
  30. */
  31. if(exp & 1) {
  32. x *= 2;
  33. exp--;
  34. }
  35. temp = 0.5 * (1.0+x);
  36. while(exp > 60) {
  37. temp *= (1L<<30);
  38. exp -= 60;
  39. }
  40. while(exp < -60) {
  41. temp /= (1L<<30);
  42. exp += 60;
  43. }
  44. if(exp >= 0)
  45. temp *= 1L << (exp/2);
  46. else
  47. temp /= 1L << (-exp/2);
  48. for(i=0; i<=4; i++)
  49. temp = 0.5*(temp + arg/temp);
  50. return temp;
  51. }