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


 
LOCAL i As Integer, x As Double, o As lanczos
CLOSE DATABASES ALL
CLEAR
CREATE CURSOR results (ZVal B(1), GamVal B(15))
INDEX ON zval TAG ZVal COLLATE "Machine"
SET ORDER TO 0
o = CREATEOBJECT("lanczos")
FOR i = 1 TO 20
x = i/10
    INSERT INTO results VALUES (x, o.Gamma(x))
ENDFOR
UPDATE results SET GamVal = ROUND(GamVal, 0) WHERE ZVal = INT(ZVal)
*!* This just creates the output text - it is not part of the algorithm
DO cursor2txt.prg WITH "results", .T.
 
DEFINE CLASS lanczos As Session
#DEFINE FPF 5.5
#DEFINE HALF 0.5
#DEFINE PY PI()
DIMENSION LanCoeff[7]
nSize = 0
 
PROCEDURE Init
DODEFAULT()
WITH THIS
    .LanCoeff[1] = 1.000000000190015
    .LanCoeff[2] = 76.18009172947146
    .LanCoeff[3] = -86.50532032941677
    .LanCoeff[4] = 24.01409824083091
    .LanCoeff[5] = -1.231739572450155
    .LanCoeff[6] = 0.0012086509738662
    .LanCoeff[7] = -0.000005395239385
    .nSize = ALEN(.LanCoeff)
ENDWITH 
ENDPROC
 
FUNCTION Gamma(z)
RETURN EXP(THIS.LogGamma(z))
ENDFUNC
 
FUNCTION LogGamma(z)
LOCAL a As Double, b As Double, i As Integer, j As Integer, lg As Double
IF z < 0.5
    lg = LOG(PY/SIN(PY*z)) - THIS.LogGamma(1 - z)
ELSE
    WITH THIS	
	z = z - 1 
	b = z + FPF
	a = .LanCoeff[1]
	FOR i = 2 TO .nSize
	    j = i - 1
	    a = a + .LanCoeff[i]/(z + j)
	ENDFOR
	lg = (LOG(SQRT(2*PY)) + LOG(a) - b) + LOG(b)*(z + HALF)
    ENDWITH	
ENDIF
RETURN lg
ENDFUNC	
 
ENDDEFINE
 