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