v / vlib / math
Raw file | 45 loc (43 sloc) | 846 bytes | Latest commit hash 1cfc4198f
1module math
2
3const (
4 tanh_p = [
5 -9.64399179425052238628e-1,
6 -9.92877231001918586564e+1,
7 -1.61468768441708447952e+3,
8 ]
9 tanh_q = [
10 1.12811678491632931402e+2,
11 2.23548839060100448583e+3,
12 4.84406305325125486048e+3,
13 ]
14)
15
16// tanh returns the hyperbolic tangent of x.
17//
18// special cases are:
19// tanh(±0) = ±0
20// tanh(±inf) = ±1
21// tanh(nan) = nan
22pub fn tanh(x f64) f64 {
23 maxlog := 8.8029691931113054295988e+01 // log(2**127)
24 mut z := abs(x)
25 if z > 0.5 * maxlog {
26 if x < 0 {
27 return f64(-1)
28 }
29 return 1.0
30 } else if z >= 0.625 {
31 s := exp(2.0 * z)
32 z = 1.0 - 2.0 / (s + 1.0)
33 if x < 0 {
34 z = -z
35 }
36 } else {
37 if x == 0 {
38 return x
39 }
40 s := x * x
41 z = x + x * s * ((math.tanh_p[0] * s + math.tanh_p[1]) * s + math.tanh_p[2]) / (((s +
42 math.tanh_q[0]) * s + math.tanh_q[1]) * s + math.tanh_q[2])
43 }
44 return z
45}