POK
tanh.c
1 /*
2  * POK header
3  *
4  * The following file is a part of the POK project. Any modification should
5  * made according to the POK licence. You CANNOT use this file or a part of
6  * this file is this part of a file for your own project
7  *
8  * For more information on the POK licence, please see our LICENCE FILE
9  *
10  * Please follow the coding guidelines described in doc/CODING_GUIDELINES
11  *
12  * Copyright (c) 2007-2009 POK team
13  *
14  * Created by julien on Fri Jan 30 14:41:34 2009
15  */
16 
17 /* @(#)s_tanh.c 5.1 93/09/24 */
18 /*
19  * ====================================================
20  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
21  *
22  * Developed at SunPro, a Sun Microsystems, Inc. business.
23  * Permission to use, copy, modify, and distribute this
24  * software is freely granted, provided that this notice
25  * is preserved.
26  * ====================================================
27  */
28 
29 #ifdef POK_NEEDS_LIBMATH
30 
31 /* Tanh(x)
32  * Return the Hyperbolic Tangent of x
33  *
34  * Method :
35  * x -x
36  * e - e
37  * 0. tanh(x) is defined to be -----------
38  * x -x
39  * e + e
40  * 1. reduce x to non-negative by tanh(-x) = -tanh(x).
41  * 2. 0 <= x <= 2**-55 : tanh(x) := x*(one+x)
42  * -t
43  * 2**-55 < x <= 1 : tanh(x) := -----; t = expm1(-2x)
44  * t + 2
45  * 2
46  * 1 <= x <= 22.0 : tanh(x) := 1- ----- ; t=expm1(2x)
47  * t + 2
48  * 22.0 < x <= INF : tanh(x) := 1.
49  *
50  * Special cases:
51  * tanh(NaN) is NaN;
52  * only tanh(0)=0 is exact for finite argument.
53  */
54 
55 #include <libm.h>
56 #include "math_private.h"
57 
58 static const double one=1.0, two=2.0, tiny = 1.0e-300;
59 
60 double
61 tanh(double x)
62 {
63  double t,z;
64  int32_t jx,ix;
65 
66  /* High word of |x|. */
67  GET_HIGH_WORD(jx,x);
68  ix = jx&0x7fffffff;
69 
70  /* x is INF or NaN */
71  if(ix>=0x7ff00000) {
72  if (jx>=0) return one/x+one; /* tanh(+-inf)=+-1 */
73  else return one/x-one; /* tanh(NaN) = NaN */
74  }
75 
76  /* |x| < 22 */
77  if (ix < 0x40360000) { /* |x|<22 */
78  if (ix<0x3c800000) /* |x|<2**-55 */
79  return x*(one+x); /* tanh(small) = small */
80  if (ix>=0x3ff00000) { /* |x|>=1 */
81  t = expm1(two*fabs(x));
82  z = one - two/(t+two);
83  } else {
84  t = expm1(-two*fabs(x));
85  z= -t/(t+two);
86  }
87  /* |x| > 22, return +-1 */
88  } else {
89  z = one - tiny; /* raised inexact flag */
90  }
91  return (jx>=0)? z: -z;
92 }
93 
94 #endif