UNPKG

2.27 kBJavaScriptView Raw
1'use strict'
2
3function factory (type, config, load, typed) {
4 const add = load(require('../arithmetic/add'))
5 const subtract = load(require('../arithmetic/subtract'))
6 const multiply = load(require('../arithmetic/multiply'))
7 const divide = load(require('../arithmetic/divide'))
8 const pow = load(require('../arithmetic/pow'))
9 const factorial = load(require('../probability/factorial'))
10 const combinations = load(require('../probability/combinations'))
11 const isNegative = load(require('../utils/isNegative'))
12 const isInteger = load(require('../utils/isInteger'))
13 const larger = load(require('../relational/larger'))
14
15 /**
16 * The Stirling numbers of the second kind, counts the number of ways to partition
17 * a set of n labelled objects into k nonempty unlabelled subsets.
18 * stirlingS2 only takes integer arguments.
19 * The following condition must be enforced: k <= n.
20 *
21 * If n = k or k = 1, then s(n,k) = 1
22 *
23 * Syntax:
24 *
25 * math.stirlingS2(n, k)
26 *
27 * Examples:
28 *
29 * math.stirlingS2(5, 3) //returns 25
30 *
31 * See also:
32 *
33 * bellNumbers
34 *
35 * @param {Number | BigNumber} n Total number of objects in the set
36 * @param {Number | BigNumber} k Number of objects in the subset
37 * @return {Number | BigNumber} S(n,k)
38 */
39 const stirlingS2 = typed('stirlingS2', {
40 'number | BigNumber, number | BigNumber': function (n, k) {
41 if (!isInteger(n) || isNegative(n) || !isInteger(k) || isNegative(k)) {
42 throw new TypeError('Non-negative integer value expected in function stirlingS2')
43 } else if (larger(k, n)) {
44 throw new TypeError('k must be less than or equal to n in function stirlingS2')
45 }
46
47 // 1/k! Sum(i=0 -> k) [(-1)^(k-i)*C(k,j)* i^n]
48 const kFactorial = factorial(k)
49 let result = 0
50 for (let i = 0; i <= k; i++) {
51 const negativeOne = pow(-1, subtract(k, i))
52 const kChooseI = combinations(k, i)
53 const iPower = pow(i, n)
54
55 result = add(result, multiply(multiply(kChooseI, iPower), negativeOne))
56 }
57
58 return divide(result, kFactorial)
59 }
60 })
61
62 stirlingS2.toTex = { 2: `\\mathrm{S}\\left(\${args}\\right)` }
63
64 return stirlingS2
65}
66
67exports.name = 'stirlingS2'
68exports.factory = factory