sqrt.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. /*
  10. sqrt returns the square root of its floating
  11. point argument. Newton's method.
  12. calls frexp
  13. */
  14. #include <u.h>
  15. #include <libc.h>
  16. double
  17. sqrt(double arg)
  18. {
  19. double x, temp;
  20. int exp, i;
  21. if(arg <= 0) {
  22. if(arg < 0)
  23. return 0.;
  24. return 0;
  25. }
  26. x = frexp(arg, &exp);
  27. while(x < 0.5) {
  28. x *= 2;
  29. exp--;
  30. }
  31. /*
  32. * NOTE
  33. * this wont work on 1's comp
  34. */
  35. if(exp & 1) {
  36. x *= 2;
  37. exp--;
  38. }
  39. temp = 0.5 * (1.0+x);
  40. while(exp > 60) {
  41. temp *= (1L<<30);
  42. exp -= 60;
  43. }
  44. while(exp < -60) {
  45. temp /= (1L<<30);
  46. exp += 60;
  47. }
  48. if(exp >= 0)
  49. temp *= 1L << (exp/2);
  50. else
  51. temp /= 1L << (-exp/2);
  52. for(i=0; i<=4; i++)
  53. temp = 0.5*(temp + arg/temp);
  54. return temp;
  55. }