ef_sqrt.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * These math functions are taken from newlib-nano-2, the newlib/libm/math
  5. * directory, available from https://github.com/32bitmicro/newlib-nano-2.
  6. *
  7. * Appropriate copyright headers are reproduced below.
  8. */
  9. /* ef_sqrtf.c -- float version of e_sqrt.c.
  10. * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
  11. */
  12. /*
  13. * ====================================================
  14. * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
  15. *
  16. * Developed at SunPro, a Sun Microsystems, Inc. business.
  17. * Permission to use, copy, modify, and distribute this
  18. * software is freely granted, provided that this notice
  19. * is preserved.
  20. * ====================================================
  21. */
  22. #include "fdlibm.h"
  23. #ifdef __STDC__
  24. static const float one = 1.0, tiny=1.0e-30;
  25. #else
  26. static float one = 1.0, tiny=1.0e-30;
  27. #endif
  28. // sqrtf is exactly __ieee754_sqrtf when _IEEE_LIBM defined
  29. float sqrtf(float x)
  30. /*
  31. #ifdef __STDC__
  32. float __ieee754_sqrtf(float x)
  33. #else
  34. float __ieee754_sqrtf(x)
  35. float x;
  36. #endif
  37. */
  38. {
  39. float z;
  40. __uint32_t r,hx;
  41. __int32_t ix,s,q,m,t,i;
  42. GET_FLOAT_WORD(ix,x);
  43. hx = ix&0x7fffffff;
  44. /* take care of Inf and NaN */
  45. if(!FLT_UWORD_IS_FINITE(hx))
  46. return x*x+x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf
  47. sqrt(-inf)=sNaN */
  48. /* take care of zero and -ves */
  49. if(FLT_UWORD_IS_ZERO(hx)) return x;/* sqrt(+-0) = +-0 */
  50. if(ix<0) return (x-x)/(x-x); /* sqrt(-ve) = sNaN */
  51. /* normalize x */
  52. m = (ix>>23);
  53. if(FLT_UWORD_IS_SUBNORMAL(hx)) { /* subnormal x */
  54. for(i=0;(ix&0x00800000L)==0;i++) ix<<=1;
  55. m -= i-1;
  56. }
  57. m -= 127; /* unbias exponent */
  58. ix = (ix&0x007fffffL)|0x00800000L;
  59. if(m&1) /* odd m, double x to make it even */
  60. ix += ix;
  61. m >>= 1; /* m = [m/2] */
  62. /* generate sqrt(x) bit by bit */
  63. ix += ix;
  64. q = s = 0; /* q = sqrt(x) */
  65. r = 0x01000000L; /* r = moving bit from right to left */
  66. while(r!=0) {
  67. t = s+r;
  68. if(t<=ix) {
  69. s = t+r;
  70. ix -= t;
  71. q += r;
  72. }
  73. ix += ix;
  74. r>>=1;
  75. }
  76. /* use floating add to find out rounding direction */
  77. if(ix!=0) {
  78. z = one-tiny; /* trigger inexact flag */
  79. if (z>=one) {
  80. z = one+tiny;
  81. if (z>one)
  82. q += 2;
  83. else
  84. q += (q&1);
  85. }
  86. }
  87. ix = (q>>1)+0x3f000000L;
  88. ix += (m <<23);
  89. SET_FLOAT_WORD(z,ix);
  90. return z;
  91. }