forked from josdejong/mathjs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.js
More file actions
91 lines (82 loc) · 2.63 KB
/
log.js
File metadata and controls
91 lines (82 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { factory } from '../../utils/factory.js'
import { logNumber } from '../../plain/number/index.js'
const name = 'log'
const dependencies = ['config', 'typed', 'typeOf', 'divideScalar', 'Complex']
const nlg16 = Math.log(16)
export const createLog = /* #__PURE__ */ factory(name, dependencies, ({ typed, typeOf, config, divideScalar, Complex }) => {
/**
* Calculate the logarithm of a value.
*
* To avoid confusion with the matrix logarithm, this function does not
* apply to matrices.
*
* Syntax:
*
* math.log(x)
* math.log(x, base)
*
* Examples:
*
* math.log(3.5) // returns 1.252762968495368
* math.exp(math.log(2.4)) // returns 2.4
*
* math.pow(10, 4) // returns 10000
* math.log(10000, 10) // returns 4
* math.log(10000) / math.log(10) // returns 4
*
* math.log(1024, 2) // returns 10
* math.pow(2, 10) // returns 1024
*
* See also:
*
* exp, log2, log10, log1p
*
* @param {number | BigNumber | Fraction | Complex} x
* Value for which to calculate the logarithm.
* @param {number | BigNumber | Fraction | Complex} [base=e]
* Optional base for the logarithm. If not provided, the natural
* logarithm of `x` is calculated.
* @return {number | BigNumber | Fraction | Complex}
* Returns the logarithm of `x`
*/
return typed(name, {
number: function (x) {
if (x >= 0 || config.predictable) {
return logNumber(x)
} else {
// negative value -> complex value computation
return new Complex(x, 0).log()
}
},
bigint: function (x) {
if (x > 0 || config.predictable) {
if (x <= 0) return NaN
const s = x.toString(16)
const s15 = s.substring(0, 15)
return nlg16 * (s.length - s15.length) + logNumber(Number('0x' + s15))
}
return new Complex(x.toNumber(), 0).log()
},
Complex: function (x) {
return x.log()
},
BigNumber: function (x) {
if (!x.isNegative() || config.predictable) {
return x.ln()
} else {
// downgrade to number, return Complex valued result
return new Complex(x.toNumber(), 0).log()
}
},
'any, any': typed.referToSelf(self => (x, base) => {
// calculate logarithm for a specified base, log(x, base)
if (typeOf(x) === 'Fraction' && typeOf(base) === 'Fraction') {
const result = x.log(base)
if (result !== null) {
return result
}
}
return divideScalar(self(x), self(base))
})
})
})