Lesson 4 of 15

Gamma Function

Gamma Function

The Gamma function Γ(n)\Gamma(n) generalizes the factorial to real (and complex) numbers:

Γ(n)=∫0∞tn−1e−t dt\Gamma(n) = \int_0^\infty t^{n-1} e^{-t}\, dt

For positive integers: Γ(n)=(n−1)!\Gamma(n) = (n-1)!

Key Properties

  • Recurrence: Γ(n+1)=n Γ(n)\Gamma(n+1) = n\, \Gamma(n)
  • Half-integer: Γ(1/2)=π\Gamma(1/2) = \sqrt{\pi}, Γ(3/2)=12π\Gamma(3/2) = \frac{1}{2}\sqrt{\pi}
  • Reflection formula: Γ(x) Γ(1−x)=πsin⁡(πx)\Gamma(x)\, \Gamma(1-x) = \frac{\pi}{\sin(\pi x)}

Stirling's Approximation

For large nn, the log-gamma function is approximated by:

ln⁡Γ(n)≈(n−12)ln⁡n−n+12ln⁡(2π)\ln \Gamma(n) \approx \left(n - \tfrac{1}{2}\right) \ln n - n + \tfrac{1}{2} \ln(2\pi)

This is the basis for log_gamma(n).

Lanczos Approximation

The Lanczos approximation computes Γ(z)\Gamma(z) accurately for positive reals using a set of precomputed coefficients. For n≥0.5n \geq 0.5, let z=n−1z = n - 1:

Γ(z+1)=2π tz+0.5 e−t Ag(z)\Gamma(z+1) = \sqrt{2\pi}\, t^{z+0.5}\, e^{-t}\, A_g(z)

where t=z+g+0.5t = z + g + 0.5 and:

Ag(z)=c0+∑k=1g+1ckz+kA_g(z) = c_0 + \sum_{k=1}^{g+1} \frac{c_k}{z + k}

For n<0.5n < 0.5, use the reflection formula:

Γ(n)=πsin⁡(πn) Γ(1−n)\Gamma(n) = \frac{\pi}{\sin(\pi n)\, \Gamma(1-n)}

Beta Function

The Beta function is defined as:

B(a,b)=Γ(a) Γ(b)Γ(a+b)=∫01ta−1(1−t)b−1 dtB(a, b) = \frac{\Gamma(a)\, \Gamma(b)}{\Gamma(a+b)} = \int_0^1 t^{a-1}(1-t)^{b-1}\, dt

It arises in probability (Beta distribution), combinatorics, and integration.

Your Task

Implement gamma using the Lanczos approximation with g=7g=7 and the 9-coefficient vector below. Implement log_gamma using Stirling's approximation. Implement beta_function using the Gamma function.

Lanczos coefficients (g=7):

[0.99999999999980993, 676.5203681218851, -1259.1392167224028,
 771.32342877765313, -176.61502916214059, 12.507343278686905,
 -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]
Python runtime loading...
Loading...
Click "Run" to execute your code.