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