sqrt.c 696 B

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