s_tanh.c 2.0 KB

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