OLD | NEW |
1 // Copyright 2009 The Go Authors. All rights reserved. | 1 // Copyright 2009 The Go Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style | 2 // Use of this source code is governed by a BSD-style |
3 // license that can be found in the LICENSE file. | 3 // license that can be found in the LICENSE file. |
4 | 4 |
5 package math | 5 package math |
6 | 6 |
7 // The original C code, the long comment, and the constants | 7 // The original C code, the long comment, and the constants |
8 // below were from http://netlib.sandia.gov/cephes/cmath/sin.c, | 8 // below were from http://netlib.sandia.gov/cephes/cmath/sin.c, |
9 // available from http://www.netlib.org/cephes/cmath.tgz. | 9 // available from http://www.netlib.org/cephes/cmath.tgz. |
10 // The go code is a simplified version of the original C. | 10 // The go code is a simplified version of the original C. |
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
58 -9.64399179425052238628E-1, | 58 -9.64399179425052238628E-1, |
59 -9.92877231001918586564E1, | 59 -9.92877231001918586564E1, |
60 -1.61468768441708447952E3, | 60 -1.61468768441708447952E3, |
61 } | 61 } |
62 var tanhQ = [...]float64{ | 62 var tanhQ = [...]float64{ |
63 1.12811678491632931402E2, | 63 1.12811678491632931402E2, |
64 2.23548839060100448583E3, | 64 2.23548839060100448583E3, |
65 4.84406305325125486048E3, | 65 4.84406305325125486048E3, |
66 } | 66 } |
67 | 67 |
68 // Tanh computes the hyperbolic tangent of x. | 68 // Tanh returns the hyperbolic tangent of x. |
69 // | 69 // |
70 // Special cases are: | 70 // Special cases are: |
71 // Tanh(±0) = ±0 | 71 // Tanh(±0) = ±0 |
72 // Tanh(±Inf) = ±1 | 72 // Tanh(±Inf) = ±1 |
73 // Tanh(NaN) = NaN | 73 // Tanh(NaN) = NaN |
74 func Tanh(x float64) float64 { | 74 func Tanh(x float64) float64 { |
75 const MAXLOG = 8.8029691931113054295988e+01 // log(2**127) | 75 const MAXLOG = 8.8029691931113054295988e+01 // log(2**127) |
76 z := Abs(x) | 76 z := Abs(x) |
77 switch { | 77 switch { |
78 case z > 0.5*MAXLOG: | 78 case z > 0.5*MAXLOG: |
79 if x < 0 { | 79 if x < 0 { |
80 return -1 | 80 return -1 |
81 } | 81 } |
82 return 1 | 82 return 1 |
83 case z >= 0.625: | 83 case z >= 0.625: |
84 s := Exp(2 * z) | 84 s := Exp(2 * z) |
85 z = 1 - 2/(s+1) | 85 z = 1 - 2/(s+1) |
86 if x < 0 { | 86 if x < 0 { |
87 z = -z | 87 z = -z |
88 } | 88 } |
89 default: | 89 default: |
90 if x == 0 { | 90 if x == 0 { |
91 return x | 91 return x |
92 } | 92 } |
93 s := x * x | 93 s := x * x |
94 z = x + x*s*((tanhP[0]*s+tanhP[1])*s+tanhP[2])/(((s+tanhQ[0])*s+
tanhQ[1])*s+tanhQ[2]) | 94 z = x + x*s*((tanhP[0]*s+tanhP[1])*s+tanhP[2])/(((s+tanhQ[0])*s+
tanhQ[1])*s+tanhQ[2]) |
95 } | 95 } |
96 return z | 96 return z |
97 } | 97 } |
OLD | NEW |