sqrt.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 NaN();
  24. return 0;
  25. }
  26. if(isInf(arg, 1))
  27. return arg;
  28. x = frexp(arg, &exp);
  29. while(x < 0.5) {
  30. x *= 2;
  31. exp--;
  32. }
  33. /*
  34. * NOTE
  35. * this wont work on 1's comp
  36. */
  37. if(exp & 1) {
  38. x *= 2;
  39. exp--;
  40. }
  41. temp = 0.5 * (1.0+x);
  42. while(exp > 60) {
  43. temp *= (1L<<30);
  44. exp -= 60;
  45. }
  46. while(exp < -60) {
  47. temp /= (1L<<30);
  48. exp += 60;
  49. }
  50. if(exp >= 0)
  51. temp *= 1L << (exp/2);
  52. else
  53. temp /= 1L << (-exp/2);
  54. for(i=0; i<=4; i++)
  55. temp = 0.5*(temp + arg/temp);
  56. return temp;
  57. }