xref: /csrg-svn/lib/libm/common_source/tanh.c (revision 42657)
1 /*
2  * Copyright (c) 1985 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  *
7  * All recipients should regard themselves as participants in an ongoing
8  * research project and hence should feel obligated to report their
9  * experiences (good or bad) with these elementary function codes, using
10  * the sendbug(8) program, to the authors.
11  */
12 
13 #ifndef lint
14 static char sccsid[] = "@(#)tanh.c	5.4 (Berkeley) 06/01/90";
15 #endif /* not lint */
16 
17 /* TANH(X)
18  * RETURN THE HYPERBOLIC TANGENT OF X
19  * DOUBLE PRECISION (VAX D FORMAT 56 BITS, IEEE DOUBLE 53 BITS)
20  * CODED IN C BY K.C. NG, 1/8/85;
21  * REVISED BY K.C. NG on 2/8/85, 2/11/85, 3/7/85, 3/24/85.
22  *
23  * Required system supported functions :
24  *	copysign(x,y)
25  *	finite(x)
26  *
27  * Required kernel function:
28  *	expm1(x)	...exp(x)-1
29  *
30  * Method :
31  *	1. reduce x to non-negative by tanh(-x) = - tanh(x).
32  *	2.
33  *	    0      <  x <=  1.e-10 :  tanh(x) := x
34  *					          -expm1(-2x)
35  *	    1.e-10 <  x <=  1      :  tanh(x) := --------------
36  *					         expm1(-2x) + 2
37  *							  2
38  *	    1      <= x <=  22.0   :  tanh(x) := 1 -  ---------------
39  *						      expm1(2x) + 2
40  *	    22.0   <  x <= INF     :  tanh(x) := 1.
41  *
42  *	Note: 22 was chosen so that fl(1.0+2/(expm1(2*22)+2)) == 1.
43  *
44  * Special cases:
45  *	tanh(NaN) is NaN;
46  *	only tanh(0)=0 is exact for finite argument.
47  *
48  * Accuracy:
49  *	tanh(x) returns the exact hyperbolic tangent of x nealy rounded.
50  *	In a test run with 1,024,000 random arguments on a VAX, the maximum
51  *	observed error was 2.22 ulps (units in the last place).
52  */
53 
54 double tanh(x)
55 double x;
56 {
57 	static double one=1.0, two=2.0, small = 1.0e-10, big = 1.0e10;
58 	double expm1(), t, copysign(), sign;
59 	int finite();
60 
61 #if !defined(vax)&&!defined(tahoe)
62 	if(x!=x) return(x);	/* x is NaN */
63 #endif	/* !defined(vax)&&!defined(tahoe) */
64 
65 	sign=copysign(one,x);
66 	x=copysign(x,one);
67 	if(x < 22.0)
68 	    if( x > one )
69 		return(copysign(one-two/(expm1(x+x)+two),sign));
70 	    else if ( x > small )
71 		{t= -expm1(-(x+x)); return(copysign(t/(two-t),sign));}
72 	    else		/* raise the INEXACT flag for non-zero x */
73 		{big+x; return(copysign(x,sign));}
74 	else if(finite(x))
75 	    return (sign+1.0E-37); /* raise the INEXACT flag */
76 	else
77 	    return(sign);	/* x is +- INF */
78 }
79