1/*
2 * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/* Tanh(x)
27 * Return the Hyperbolic Tangent of x
28 *
29 * Method :
30 * x -x
31 * e - e
32 * 0. tanh(x) is defined to be -----------
33 * x -x
34 * e + e
35 * 1. reduce x to non-negative by tanh(-x) = -tanh(x).
36 * 2. 0 <= x <= 2**-55 : tanh(x) := x*(one+x)
37 * -t
38 * 2**-55 < x <= 1 : tanh(x) := -----; t = expm1(-2x)
39 * t + 2
40 * 2
41 * 1 <= x <= 22.0 : tanh(x) := 1- ----- ; t=expm1(2x)
42 * t + 2
43 * 22.0 < x <= INF : tanh(x) := 1.
44 *
45 * Special cases:
46 * tanh(NaN) is NaN;
47 * only tanh(0)=0 is exact for finite argument.
48 */
49
50#include "fdlibm.h"
51
52#ifdef __STDC__
53static const double one=1.0, two=2.0, tiny = 1.0e-300;
54#else
55static double one=1.0, two=2.0, tiny = 1.0e-300;
56#endif
57
58#ifdef __STDC__
59 double tanh(double x)
60#else
61 double tanh(x)
62 double x;
63#endif
64{
65 double t,z;
66 int jx,ix;
67
68 /* High word of |x|. */
69 jx = __HI(x);
70 ix = jx&0x7fffffff;
71
72 /* x is INF or NaN */
73 if(ix>=0x7ff00000) {
74 if (jx>=0) return one/x+one; /* tanh(+-inf)=+-1 */
75 else return one/x-one; /* tanh(NaN) = NaN */
76 }
77
78 /* |x| < 22 */
79 if (ix < 0x40360000) { /* |x|<22 */
80 if (ix<0x3c800000) /* |x|<2**-55 */
81 return x*(one+x); /* tanh(small) = small */
82 if (ix>=0x3ff00000) { /* |x|>=1 */
83 t = expm1(two*fabs(x));
84 z = one - two/(t+two);
85 } else {
86 t = expm1(-two*fabs(x));
87 z= -t/(t+two);
88 }
89 /* |x| > 22, return +-1 */
90 } else {
91 z = one - tiny; /* raised inexact flag */
92 }
93 return (jx>=0)? z: -z;
94}
95