tanh.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* origin: FreeBSD /usr/src/lib/msun/src/s_tanh.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. /* Tanh(x)
  13. * Return the Hyperbolic Tangent of x
  14. *
  15. * Method :
  16. * x -x
  17. * e - e
  18. * 0. tanh(x) is defined to be -----------
  19. * x -x
  20. * e + e
  21. * 1. reduce x to non-negative by tanh(-x) = -tanh(x).
  22. * 2. 0 <= x < 2**-28 : tanh(x) := x with inexact if x != 0
  23. * -t
  24. * 2**-28 <= x < 1 : tanh(x) := -----; t = expm1(-2x)
  25. * t + 2
  26. * 2
  27. * 1 <= x < 22 : tanh(x) := 1 - -----; t = expm1(2x)
  28. * t + 2
  29. * 22 <= x <= INF : tanh(x) := 1.
  30. *
  31. * Special cases:
  32. * tanh(NaN) is NaN;
  33. * only tanh(0)=0 is exact for finite argument.
  34. */
  35. #include "libm.h"
  36. static const double tiny = 1.0e-300, huge = 1.0e300;
  37. double tanh(double x)
  38. {
  39. double t,z;
  40. int32_t jx,ix;
  41. GET_HIGH_WORD(jx, x);
  42. ix = jx & 0x7fffffff;
  43. /* x is INF or NaN */
  44. if (ix >= 0x7ff00000) {
  45. if (jx >= 0)
  46. return 1.0f/x + 1.0f; /* tanh(+-inf)=+-1 */
  47. else
  48. return 1.0f/x - 1.0f; /* tanh(NaN) = NaN */
  49. }
  50. if (ix < 0x40360000) { /* |x| < 22 */
  51. if (ix < 0x3e300000) { /* |x| < 2**-28 */
  52. /* tanh(tiny) = tiny with inexact */
  53. if (huge+x > 1.0f)
  54. return x;
  55. }
  56. if (ix >= 0x3ff00000) { /* |x| >= 1 */
  57. t = expm1(2.0f*fabs(x));
  58. z = 1.0f - 2.0f/(t+2.0f);
  59. } else {
  60. t = expm1(-2.0f*fabs(x));
  61. z= -t/(t+2.0f);
  62. }
  63. } else { /* |x| >= 22, return +-1 */
  64. z = 1.0f - tiny; /* raise inexact */
  65. }
  66. return jx >= 0 ? z : -z;
  67. }