1 |
|
2 |
|
3 | const deepMap = require('../../utils/collection/deepMap')
|
4 |
|
5 | function factory (type, config, load, typed) {
|
6 | /**
|
7 | * Calculate the hyperbolic tangent of a value,
|
8 | * defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`.
|
9 | *
|
10 | * For matrices, the function is evaluated element wise.
|
11 | *
|
12 | * Syntax:
|
13 | *
|
14 | * math.tanh(x)
|
15 | *
|
16 | * Examples:
|
17 | *
|
18 | * // tanh(x) = sinh(x) / cosh(x) = 1 / coth(x)
|
19 | * math.tanh(0.5) // returns 0.46211715726000974
|
20 | * math.sinh(0.5) / math.cosh(0.5) // returns 0.46211715726000974
|
21 | * 1 / math.coth(0.5) // returns 0.46211715726000974
|
22 | *
|
23 | * See also:
|
24 | *
|
25 | * sinh, cosh, coth
|
26 | *
|
27 | * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
|
28 | * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic tangent of x
|
29 | */
|
30 | const tanh = typed('tanh', {
|
31 | 'number': _tanh,
|
32 |
|
33 | 'Complex': function (x) {
|
34 | return x.tanh()
|
35 | },
|
36 |
|
37 | 'BigNumber': function (x) {
|
38 | return x.tanh()
|
39 | },
|
40 |
|
41 | 'Unit': function (x) {
|
42 | if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
|
43 | throw new TypeError('Unit in function tanh is no angle')
|
44 | }
|
45 | return tanh(x.value)
|
46 | },
|
47 |
|
48 | 'Array | Matrix': function (x) {
|
49 | // deep map collection, skip zeros since tanh(0) = 0
|
50 | return deepMap(x, tanh, true)
|
51 | }
|
52 | })
|
53 |
|
54 | tanh.toTex = { 1: `\\tanh\\left(\${args[0]}\\right)` }
|
55 |
|
56 | return tanh
|
57 | }
|
58 |
|
59 | /**
|
60 | * Calculate the hyperbolic tangent of a number
|
61 | * @param {number} x
|
62 | * @returns {number}
|
63 | * @private
|
64 | */
|
65 | const _tanh = Math.tanh || function (x) {
|
66 | const e = Math.exp(2 * x)
|
67 | return (e - 1) / (e + 1)
|
68 | }
|
69 |
|
70 | exports.name = 'tanh'
|
71 | exports.factory = factory
|