gitee.com/quant1x/num@v0.3.2/math32/tanh.go (about) 1 package math32 2 3 // The original C code, the long comment, and the constants 4 // below were from http://netlib.sandia.gov/cephes/cmath/tanh.c, 5 // available from http://www.netlib.org/cephes/single.tgz. 6 // The go code is a simplified version of the original C. 7 // tanhf.c 8 // 9 // Hyperbolic tangent 10 // 11 // 12 // 13 // SYNOPSIS: 14 // 15 // float x, y, tanhf(); 16 // 17 // y = tanhf( x ); 18 // 19 // 20 // 21 // DESCRIPTION: 22 // 23 // Returns hyperbolic tangent of argument in the range MINLOG to 24 // MAXLOG. 25 // 26 // A polynomial approximation is used for |x| < 0.625. 27 // Otherwise, 28 // 29 // tanh(x) = sinh(x)/cosh(x) = 1 - 2/(exp(2x) + 1). 30 // 31 // 32 // 33 // ACCURACY: 34 // 35 // Relative error: 36 // arithmetic domain # trials peak rms 37 // IEEE -2,2 100000 1.3e-7 2.6e-8 38 // 39 // 40 41 /* 42 Cephes Math Library Release 2.2: June, 1992 43 Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier 44 Direct inquiries to 30 Frost Street, Cambridge, MA 02140 45 */ 46 47 /* Single precision hyperbolic tangent 48 * test interval: [-0.625, +0.625] 49 * trials: 10000 50 * peak relative error: 7.2e-8 51 * rms relative error: 2.6e-8 52 */ 53 54 func Tanh(x float32) float32 { 55 const MAXLOG = 88.02969187150841 56 z := Abs(x) 57 switch { 58 case z > 0.5*MAXLOG: 59 if x < 0 { 60 return -1 61 } 62 return 1 63 case z >= 0.625: 64 s := Exp(z + z) 65 z = 1 - 2/(s+1) 66 if x < 0 { 67 z = -z 68 } 69 default: 70 if x == 0 { 71 return x 72 } 73 s := x * x 74 z = ((((-5.70498872745e-3*s+2.06390887954e-2)*s-5.37397155531e-2)*s+1.33314422036e-1)*s-3.33332819422e-1)*s*x + x 75 } 76 return z 77 }