Task

Implement one algorithm (or more) to compute the Gamma (



Γ


{\displaystyle \Gamma }

) function (in the real field only).

If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.

The Gamma function can be defined as:

  



Γ
(
x
)
=


∫

0


∞



t

x
−
1



e

−
t


d
t



{\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt}


This suggests a straightforward (but inefficient) way of computing the 



Γ


{\displaystyle \Gamma }

 through numerical integration.



Better suggested methods:

 Lanczos approximation
 Stirling's approximation


mata
_gamma_coef = 1.0,
 5.772156649015328606065121e-1,
-6.558780715202538810770195e-1,
-4.200263503409523552900393e-2,
 1.665386113822914895017008e-1,
-4.219773455554433674820830e-2,
-9.621971527876973562114922e-3,
 7.218943246663099542395010e-3,
-1.165167591859065112113971e-3,
-2.152416741149509728157300e-4,
 1.280502823881161861531986e-4,
-2.013485478078823865568939e-5,
-1.250493482142670657345359e-6,
 1.133027231981695882374130e-6,
-2.056338416977607103450154e-7,
 6.116095104481415817862499e-9,
 5.002007644469222930055665e-9,
-1.181274570487020144588127e-9,
 1.04342671169110051049154e-10,
 7.782263439905071254049937e-12,
-3.696805618642205708187816e-12,
 5.100370287454475979015481e-13,
-2.05832605356650678322243e-14,
-5.348122539423017982370017e-15,
 1.226778628238260790158894e-15,
-1.181259301697458769513765e-16,
 1.186692254751600332579777e-18,
 1.412380655318031781555804e-18,
-2.298745684435370206592479e-19,
 1.714406321927337433383963e-20
 
function gamma_(x_) {
    external _gamma_coef
    x = x_
    y = 1
    while (x<0.5) y = y/x++
    while (x>1.5) y = --x*y
    z = _gamma_coef[30]
    x--
    for (i=29; i>=1; i--) z = z*x+_gamma_coef[i]
    return(y/z)
}
 
function map(f,a) {
    n = rows(a)
    p = cols(a)
    b = J(n,p,.)
    for (i=1; i<=n; i++) {
        for (j=1; j<=p; j++) {
            b[i,j] = (*f)(a[i,j])
        }
    }
    return(b)
}
 
x=(1::1000)/100
u=map(&gamma(),x)
v=map(&gamma_(),x)
max(abs((v-u):/u))
end