Logo

SQL Server STIRLING2 Function

Updated 2024-03-14 20:29:45.457000

Description

Use the scalar function STIRLING2 to calculate the Stirling numbers of the second kind. The Stirling numbers of the second kind count the number of ways to partition n elements into k nonempty sets:

\left\{ {n \atop k}\right\} = \frac{1}{k!}\sum_{i=0}^k (-1)^{k-i} \binom{k}{i} i^n = \sum_{i=0}^k \frac{(-1)^{k-i} i^n}{(k-i)!i!}

Where

\binom{k}{i}

is the binomial coefficient (see BICO). Stirling numbers of the second kind exhibit the following recursive relationship.

\left\{{n+1\atop k}\right\} = k \left\{{ n \atop k }\right\} + \left\{{n\atop k-1}\right\} \quad \mbox{for} \; 0<k<n

Syntax

SELECT [westclintech].[wct].[STIRLING2] (
   <@n, int,>
  ,<@k, int,>)

Arguments

@n

Number of items.

@k

Number chosen.

Return Type

float

Remarks

If n <= 0 then NULL is returned.

If k < 0 then NULL is returned.

If k > n then NULL is returned.

S(0,0) = 1.

S(n,0) = 0.

Examples

Example #1

Let's say that we have a fair die and we roll it 10 times. We can use the Stirling numbers of the second kind to predict the probability that the result set will contain 1, 2, 3, 4, 5 or 6 distinct values.

SELECT k.SeriesValue as [N],
       wct.BICO(6, k.seriesvalue) * wct.STIRLING2(10, k.seriesvalue) * wct.FACT(
                 k.SeriesValue) * wct.POWER(6, -10) as p
FROM wct.Seriesint(1, 6, NULL, NULL, NULL) k;

This produces the following result.

Np
19.92290301275212E-08
20.000253530171975817
30.0185161370217955
40.203052364349947
50.506365740740741
60.271812128486511

[Example #2](./Example #2) A lower triangular representation of the first few Stirling numbers of the second kind.

SELECT [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9],
       [10]
FROM
(
    SELECT n.SeriesValue as n,
           k.seriesValue as k,
           cast(wct.STIRLING2(n.SeriesValue, k.SeriesValue) as int) as S1
    FROM wct.SeriesInt(1, 10, NULL, NULL, NULL) n
        CROSS APPLY wct.SeriesInt(1, n.seriesvalue, NULL, NULL, NULL) k
) d
PIVOT
(
    MAX(S1)
    FOR k IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10])
) pvt
ORDER BY n;

This produces the following result.

12345678910
1NULLNULLNULLNULLNULLNULLNULLNULLNULL
11NULLNULLNULLNULLNULLNULLNULLNULL
131NULLNULLNULLNULLNULLNULLNULL
1761NULLNULLNULLNULLNULLNULL
11525101NULLNULLNULLNULLNULL
1319065151NULLNULLNULLNULL
163301350140211NULLNULLNULL
112796617011050266281NULLNULL
12553025777069512646462361NULL
151193303410542525228275880750451

See Also

FACTORIALPOWER - the step-h factorial power x(n,h)

LCHOOSE - Natural logarithm of the binomial coefficient

LPERMUTA - calculate the natural logarithm of the PERMUTATIONA function.

PERMUT - calculate the number of permutations for a given number objects that can be selected from a number of objects

PERMUTATIONA - number of permutations with repetition

STIRLING1 - Stirling numbers of the first kind