Lanczos approximation


In mathematics, the Lanczos approximation is a method for computing the gamma function numerically, published by Cornelius Lanczos in 1964. It is a practical alternative to the more popular Stirling's approximation for calculating the gamma function with fixed precision.

Introduction

The Lanczos approximation consists of the formula
for the gamma function, with
Here g is a constant that may be chosen arbitrarily subject to the restriction that Re > . The coefficients p, which depend on g, are slightly more difficult to calculate. Although the formula as stated here is only valid for arguments in the right complex half-plane, it can be extended to the entire complex plane by the reflection formula,
The series A is convergent, and may be truncated to obtain an approximation with the desired precision. By choosing an appropriate g, only some 5–10 terms of the series are needed to compute the gamma function with typical single or double floating-point precision. If a fixed g is chosen, the coefficients can be calculated in advance and the sum is recast into the following form:
Thus computing the gamma function becomes a matter of evaluating only a small number of elementary functions and multiplying by stored constants. The Lanczos approximation was popularized by Numerical Recipes, according to which computing the gamma function becomes "not much more difficult than other built-in functions that we take for granted, such as sin x or ex". The method is also implemented in the GNU Scientific Library.

Coefficients

The coefficients are given by
where represents the th element of the matrix of coefficients for the Chebyshev polynomials, which can be calculated recursively from these identities:
Godfrey describes how to obtain the coefficients and also the value of the truncated series A as a matrix product.

Derivation

Lanczos derived the formula from Leonhard Euler's integral
performing a sequence of basic manipulations to obtain
and deriving a series for the integral.

Simple implementation

The following implementation in the Python programming language works for complex arguments and typically gives 15 correct decimal places.
Note that omitting the smallest coefficients does not result in a faster but slightly less accurate implementation; the coefficients must be recomputed from scratch for an expansion with fewer terms.

from cmath import sin, sqrt, pi, exp
p =
EPSILON = 1e-07
def drop_imag:
if abs <= EPSILON:
z = z.real
return z
def gamma:
z = complex
if z.real < 0.5:
y = pi / * gamma) # Reflection formula
else:
z -= 1
x = 0.99999999999980993
for in enumerate:
x += pval /
t = z + len - 0.5
y = sqrt * t** * exp * x
return drop_imag
"""
The above use of the reflection is necessary, even though
it may look strange, as it allows to extend the approximation to values of z where
Re < 0.5, where the Lanczos method is not valid.
"""
print
print
print