summaryrefslogtreecommitdiff
path: root/sterling_approx.awk
blob: cb5f56387aa279888083358eb84eec77098b7e25 (plain) (blame)
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
#!/usr/bin/awk -f


# https://en.wikipedia.org/wiki/Sterling_Approximation
# An alternative approximation for the Gamma function stated by Srinivasa
# Ramanujan (Ramanujan 1988) is
#    Gamma(1+x) ~= sqrt(pi)((x/e)^x)(8x^3 + 4x^2 + x + 1/30)^(1/6)
# for x >= 0. The equivalent approximation for ln(n!) has an asymptotic error
# of 1/(1400*n^3) ...


### sterling_approx.awk
# https://en.wikipedia.org/wiki/Stirling%27s_approximation

function pwr(x, p) {
    return p ? exp(p*log(x)) : 1
}

BEGIN {
    ARGV[1] ? n = ARGV[1] : n = 0
    ARGV[2] ? OFMT = "%." ARGV[2] "g" : OFMT = "%g"
    pi = 4*atan2(1,1)
    f = 0
    if (n > 0) {
        f = sqrt(2*pi*n)*pwr(n*exp(-1), n)*(1 + 1/(12*n) + 1/(288*n*n) - 139/(51840*n*n*n) - 571/(2488320*n*n*n*n))
    }
    printf(OFMT ORS, f)
}