sqrt.c 711 B

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