sqrt.c 675 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 0.;
  16. return 0;
  17. }
  18. x = frexp(arg, &exp);
  19. while(x < 0.5) {
  20. x *= 2;
  21. exp--;
  22. }
  23. /*
  24. * NOTE
  25. * this wont work on 1's comp
  26. */
  27. if(exp & 1) {
  28. x *= 2;
  29. exp--;
  30. }
  31. temp = 0.5 * (1.0+x);
  32. while(exp > 60) {
  33. temp *= (1L<<30);
  34. exp -= 60;
  35. }
  36. while(exp < -60) {
  37. temp /= (1L<<30);
  38. exp += 60;
  39. }
  40. if(exp >= 0)
  41. temp *= 1L << (exp/2);
  42. else
  43. temp /= 1L << (-exp/2);
  44. for(i=0; i<=4; i++)
  45. temp = 0.5*(temp + arg/temp);
  46. return temp;
  47. }