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