log2f.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* origin: FreeBSD /usr/src/lib/msun/src/e_log2f.c */
  2. /*
  3. * ====================================================
  4. * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
  5. *
  6. * Developed at SunPro, a Sun Microsystems, Inc. business.
  7. * Permission to use, copy, modify, and distribute this
  8. * software is freely granted, provided that this notice
  9. * is preserved.
  10. * ====================================================
  11. */
  12. /*
  13. * See comments in log2.c.
  14. */
  15. #include "libm.h"
  16. #include "__log1pf.h"
  17. static const float
  18. two25 = 3.3554432000e+07, /* 0x4c000000 */
  19. ivln2hi = 1.4428710938e+00, /* 0x3fb8b000 */
  20. ivln2lo = -1.7605285393e-04; /* 0xb9389ad4 */
  21. float log2f(float x)
  22. {
  23. float f,hfsq,hi,lo,r,y;
  24. int32_t i,k,hx;
  25. GET_FLOAT_WORD(hx, x);
  26. k = 0;
  27. if (hx < 0x00800000) { /* x < 2**-126 */
  28. if ((hx&0x7fffffff) == 0)
  29. return -two25/0.0f; /* log(+-0)=-inf */
  30. if (hx < 0)
  31. return (x-x)/0.0f; /* log(-#) = NaN */
  32. /* subnormal number, scale up x */
  33. k -= 25;
  34. x *= two25;
  35. GET_FLOAT_WORD(hx, x);
  36. }
  37. if (hx >= 0x7f800000)
  38. return x+x;
  39. if (hx == 0x3f800000)
  40. return 0.0f; /* log(1) = +0 */
  41. k += (hx>>23) - 127;
  42. hx &= 0x007fffff;
  43. i = (hx+(0x4afb0d))&0x800000;
  44. SET_FLOAT_WORD(x, hx|(i^0x3f800000)); /* normalize x or x/2 */
  45. k += i>>23;
  46. y = (float)k;
  47. f = x - 1.0f;
  48. hfsq = 0.5f * f * f;
  49. r = __log1pf(f);
  50. /*
  51. * We no longer need to avoid falling into the multi-precision
  52. * calculations due to compiler bugs breaking Dekker's theorem.
  53. * Keep avoiding this as an optimization. See log2.c for more
  54. * details (some details are here only because the optimization
  55. * is not yet available in double precision).
  56. *
  57. * Another compiler bug turned up. With gcc on i386,
  58. * (ivln2lo + ivln2hi) would be evaluated in float precision
  59. * despite runtime evaluations using double precision. So we
  60. * must cast one of its terms to float_t. This makes the whole
  61. * expression have type float_t, so return is forced to waste
  62. * time clobbering its extra precision.
  63. */
  64. // FIXME
  65. // if (sizeof(float_t) > sizeof(float))
  66. // return (r - hfsq + f) * ((float_t)ivln2lo + ivln2hi) + y;
  67. hi = f - hfsq;
  68. GET_FLOAT_WORD(hx,hi);
  69. SET_FLOAT_WORD(hi,hx&0xfffff000);
  70. lo = (f - hi) - hfsq + r;
  71. return (lo+hi)*ivln2lo + lo*ivln2hi + hi*ivln2hi + y;
  72. }