s_tanh.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * ====================================================
  3. * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
  4. *
  5. * Developed at SunPro, a Sun Microsystems, Inc. business.
  6. * Permission to use, copy, modify, and distribute this
  7. * software is freely granted, provided that this notice
  8. * is preserved.
  9. * ====================================================
  10. */
  11. /* Tanh(x)
  12. * Return the Hyperbolic Tangent of x
  13. *
  14. * Method :
  15. * x -x
  16. * e - e
  17. * 0. tanh(x) is defined to be -----------
  18. * x -x
  19. * e + e
  20. * 1. reduce x to non-negative by tanh(-x) = -tanh(x).
  21. * 2. 0 <= x <= 2**-55 : tanh(x) := x*(one+x)
  22. * -t
  23. * 2**-55 < x <= 1 : tanh(x) := -----; t = expm1(-2x)
  24. * t + 2
  25. * 2
  26. * 1 <= x <= 22.0 : tanh(x) := 1- ----- ; t=expm1(2x)
  27. * t + 2
  28. * 22.0 < x <= INF : tanh(x) := 1.
  29. *
  30. * Special cases:
  31. * tanh(NaN) is NaN;
  32. * only tanh(0)=0 is exact for finite argument.
  33. */
  34. #include "math.h"
  35. #include "math_private.h"
  36. static const double one=1.0, two=2.0, tiny = 1.0e-300;
  37. double tanh(double x)
  38. {
  39. double t,z;
  40. int32_t jx,ix;
  41. /* High word of |x|. */
  42. GET_HIGH_WORD(jx,x);
  43. ix = jx&0x7fffffff;
  44. /* x is INF or NaN */
  45. if(ix>=0x7ff00000) {
  46. if (jx>=0) return one/x+one; /* tanh(+-inf)=+-1 */
  47. else return one/x-one; /* tanh(NaN) = NaN */
  48. }
  49. /* |x| < 22 */
  50. if (ix < 0x40360000) { /* |x|<22 */
  51. if (ix<0x3c800000) /* |x|<2**-55 */
  52. return x*(one+x); /* tanh(small) = small */
  53. if (ix>=0x3ff00000) { /* |x|>=1 */
  54. t = expm1(two*fabs(x));
  55. z = one - two/(t+two);
  56. } else {
  57. t = expm1(-two*fabs(x));
  58. z= -t/(t+two);
  59. }
  60. /* |x| > 22, return +-1 */
  61. } else {
  62. z = one - tiny; /* raised inexact flag */
  63. }
  64. return (jx>=0)? z: -z;
  65. }
  66. libm_hidden_def(tanh)