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 real constant that may be chosen arbitrarily subject to the restriction that Re(z+g+1/2) > 0.[1] The coefficients p, which depend on g, are slightly more difficult to calculate (see below). 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 (typically a small integer), 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, thanks to partial fraction decomposition, 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, Boost, CPython and musl.

Coefficients

The coefficients are given by

where represents the (n, m)th element of the matrix of coefficients for the Chebyshev polynomials, which can be calculated recursively from these identities:

Godfrey (2001) describes how to obtain the coefficients and also the value of the truncated series A as a matrix product.[2]

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 13 correct decimal places. Note that omitting the smallest coefficients (in pursuit of speed, for example) gives totally inaccurate results; the coefficients must be recomputed from scratch for an expansion with fewer terms.

from cmath import sin, sqrt, pi, exp


"""
The coefficients used in the code are for when g = 7 and n = 9
Here are some other samples

g = 5
n = 5
p = [
    1.0000018972739440364,
    76.180082222642137322,
    -86.505092037054859197,
    24.012898581922685900,
    -1.2296028490285820771
]

g = 5
n = 7
p = [
    1.0000000001900148240,
    76.180091729471463483,
    -86.505320329416767652,
    24.014098240830910490,
    -1.2317395724501553875,
    0.0012086509738661785061,
    -5.3952393849531283785e-6
]

g = 8
n = 12
p = [
    0.9999999999999999298,
    1975.3739023578852322,
    -4397.3823927922428918,
    3462.6328459862717019,
    -1156.9851431631167820,
    154.53815050252775060,
    -6.2536716123689161798,
    0.034642762454736807441,
    -7.4776171974442977377e-7,
    6.3041253821852264261e-8,
    -2.7405717035683877489e-8,
    4.0486948817567609101e-9
]
"""

g = 7
n = 9
p = [
    0.99999999999980993,
    676.5203681218851,
    -1259.1392167224028,
    771.32342877765313,
    -176.61502916214059,
    12.507343278686905,
    -0.13857109526572012,
    9.9843695780195716e-6,
    1.5056327351493116e-7
]

EPSILON = 1e-07
def drop_imag(z):
    if abs(z.imag) <= EPSILON:
        z = z.real
    return z

def gamma(z):
    z = complex(z)
    if z.real < 0.5:
        y = pi / (sin(pi * z) * gamma(1 - z))  # Reflection formula
    else:
        z -= 1
        x = p[0]
        for i in range(1, len(p)):
            x += p[i] / (z + i)
        t = z + g + 0.5
        y = sqrt(2 * pi) * t ** (z + 0.5) * exp(-t) * x
    return drop_imag(y)
"""
The above use of the reflection (thus the if-else structure) is necessary, even though 
it may look strange, as it allows to extend the approximation to values of z where 
Re(z) < 0.5, where the Lanczos method is not valid.
"""

print(gamma(1))
print(gamma(5))   
print(gamma(0.5))

See also

References

  1. ^ Pugh, Glendon (2004). An analysis of the Lanczos Gamma approximation (PDF) (Ph.D.).
  2. ^ Godfrey, Paul (2001). "Lanczos implementation of the gamma function". Numericana.

Read other articles:

dr.Fahmi Fadli Bupati Paser ke-8PetahanaMulai menjabat 26 Februari 2021PresidenJoko WidodoGubernurIsran Noor PendahuluYusriansyah SyarkawiKatsul Wijaya (Plh.)PenggantiPetahana Informasi pribadiLahir3 Maret 1976 (umur 48)Balikpapan, Kalimantan TimurKebangsaanIndonesiaPartai politik PDP (2008-2013)PKPI (2013-2015)PKB (2016-sekarang)Suami/istriSinta Rosma YentiAnak2Alma materUniversitas Muhammadiyah YogyakartaSunting kotak info • L • B dr. Fahmi Fadli (lahir 3 Maret 19...

 

本條目存在以下問題,請協助改善本條目或在討論頁針對議題發表看法。 此條目需要补充更多来源。 (2018年3月17日)请协助補充多方面可靠来源以改善这篇条目,无法查证的内容可能會因為异议提出而被移除。致使用者:请搜索一下条目的标题(来源搜索:羅生門 (電影) — 网页、新闻、书籍、学术、图像),以检查网络上是否存在该主题的更多可靠来源(判定指引)。 �...

 

Al-Marwah, (Riyadh)PermukimanAl-Marwah, (Riyadh)Location in the Kingdom of Saudi ArabiaKoordinat: 24°38′N 46°43′E / 24.633°N 46.717°E / 24.633; 46.717Koordinat: 24°38′N 46°43′E / 24.633°N 46.717°E / 24.633; 46.717Negara Arab SaudiPemerintahan • Gubernur Pangeran RiyadhFaisal bin Bandar Al Saud • Wali kotaIbraheem Mohammed Al-SultanKetinggian612 m (2,008 ft)Zona waktuUTC+3 (AST) • ...

Indoor exhibition center in New Jersey, United States Asbury Park Convention HallAddress1300 Ocean AvenueLocationAsbury Park, New JerseyPublic transitNJ Transit at Asbury Park station   North Jersey Coast Line NJT Bus: 832, 837 Asbury Park Convention HallU.S. National Register of Historic PlacesNew Jersey Register of Historic Places Show map of Monmouth County, New JerseyShow map of New JerseyShow map of the United StatesLocationOcean Avenue, Asbury Park, New JerseyCoordinates40°13...

 

Pastri sus yang berbentuk angsa dan yang berbentuk bulat. Adonan sus (Bahasa Inggris:Choux pastry atau Choux paste) adalah adonan yang dibuat dengan menggunakan mentega, air, tepung terigu dan telur.[1] Selain itu, gula dan garam dapat ditambahkan ke dalam adonan tersebut.[1] Nama adonan ini berasal dari bahasa Prancis yaitu Pâte à choux yang secara literal berarti pasta kubis karena bentuk akhirnya yang menyerupai kubis.[2] Sementara itu, adonan ini sering disebut s...

 

Residential building in Manhattan, New York This article's tone or style may not reflect the encyclopedic tone used on Wikipedia. See Wikipedia's guide to writing better articles for suggestions. (February 2013) (Learn how and when to remove this message) 998 Fifth AvenueGeneral informationTypeResidentialArchitectural styleItalian RenaissanceLocationUpper East Side, Manhattan, New York City, U.S.Coordinates40°46′42″N 73°57′44″W / 40.7783°N 73.9622°W / 40.77...

ХристианствоБиблия Ветхий Завет Новый Завет Евангелие Десять заповедей Нагорная проповедь Апокрифы Бог, Троица Бог Отец Иисус Христос Святой Дух История христианства Апостолы Хронология христианства Раннее христианство Гностическое христианство Вселенские соборы Н...

 

この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)出典検索?: コルク – ニュース · 書籍 · スカラー · CiNii · J-STAGE · NDL · dlib.jp · ジャパンサーチ · TWL(2017年4月) コルクを打ち抜いて作った瓶の栓 コルク(木栓、�...

 

Ця стаття потребує додаткових посилань на джерела для поліпшення її перевірності. Будь ласка, допоможіть удосконалити цю статтю, додавши посилання на надійні (авторитетні) джерела. Зверніться на сторінку обговорення за поясненнями та допоможіть виправити недоліки. Мат...

「アプリケーション」はこの項目へ転送されています。英語の意味については「wikt:応用」、「wikt:application」をご覧ください。 この記事には複数の問題があります。改善やノートページでの議論にご協力ください。 出典がまったく示されていないか不十分です。内容に関する文献や情報源が必要です。(2018年4月) 古い情報を更新する必要があります。(2021年3月)出...

 

Robin Gosens Gosens pada 2018Informasi pribadiNama lengkap Robin Everardus Gosens[1]Tanggal lahir 5 Juli 1994 (umur 29)Tempat lahir Emmerich am Rhein, JermanTinggi 1,83 m (6 ft 0 in)[2]Posisi bermain Gelandang kiri, Bek sayap kiri[3][4]Informasi klubKlub saat ini Union BerlinNomor 6Karier junior2000–2007 Fortuna Elten2007–2009 1. FC Bocholt2009–2012 VfL Rhede2012–2014 VitesseKarier senior*Tahun Tim Tampil (Gol)2014–2015 Vitesse 0 ...

 

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: 1830 in the United States – news · newspapers · books · scholar · JSTOR (December 2021) (Learn how and when to remove this message) List of events ← 1829 1828 1827 1830 in the United States → 1831 1832 1833 Decades: 1810s 1820s 1830s 1840s 1850s See...

Mexican architect (1905–1987) This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Enrique del Moral – news · newspapers · books · scholar · JSTOR (April 2022...

 

Afrika Selatan padaOlimpiadeKode IOCRSAKONKomite Olimpiade dan Konferensi Olahraga Afrika SelatanSitus webwww.sascoc.co.zaMedali 27 33 29 Total 89 Penampilan Musim Panas1904190819121920192419281932193619481952195619601964–198819921996200020042008201220162020Penampilan Musim Dingin19601964–199219941998200220062010201420182022 Afrika Selatan mula-mula berpartisipasi dalam Permainan Olimpiade pada 1904, dan mengirim para atlet untuk berkompetisi dalam setiap Permainan Olimpiade Musim Panas s...

 

Lambang Komune Saâcy-sur-Marne. Saâcy-sur-MarneNegaraPrancisArondisemenMeauxKantonLa Ferté-sous-JouarreAntarkomuneCommunauté de communes du Pays FertoisPemerintahan • Wali kota (2008-2014) Josselyne Robcis • Populasi11.658Kode INSEE/pos77397 / 2 Population sans doubles comptes: penghitungan tunggal penduduk di komune lain (e.g. mahasiswa dan personil militer). Saâcy-sur-Marne merupakan sebuah komune di departemen Seine-et-Marne di region Île-de-France di uta...

Chinese diver (born 1995) Chen AisenChen Aisen and Lin Yue at the Rio OlympicsPersonal informationNative name陈艾森NationalityChineseBorn (1995-10-22) 22 October 1995 (age 28)Guangzhou, ChinaHeight1.68 m (5 ft 6 in)Weight60 kg (132 lb)SportCountryChinaSportDivingEvent(s)10 m, 10 m synchroClubGuangdong Province Medal record Men's diving Representing  China Event 1st 2nd 3rd Olympic Games 2 1 0 World Championships 3 1 0 FINA Diving World Cup 3 1 0 Tota...

 

В Википедии есть статьи о других людях с такой фамилией, см. Попов; Попов, Пётр. Пётр Харитонович Попов Дата рождения 10 (22) января 1867(1867-01-22) Место рождения Новочеркасск, Область Войска Донского Дата смерти 6 октября 1960(1960-10-06) (93 года) Место смерти Нью-Йорк, США Род деятел�...

 

Tallahassee Tennis Challenger 2008Sport Tennis Dataaprile - aprile Edizione9° SuperficieCemento CampioniSingolare Bobby Reynolds Doppio Rajeev Rami / Bobby Reynolds 2007 2009 Il Tallahassee Tennis Challenger 2008 è stato un torneo di tennis facente parte della categoria ATP Challenger Series nell'ambito dell'ATP Challenger Series 2008. Il torneo si è giocato a Tallahassee negli Stati Uniti dal al aprile 2008 su campi in cemento e aveva un montepremi di $50 000. Indice 1 Vincitori 1.1 Singo...

German General Second World War Wilhelm WetzelBorn(1888-07-17)17 July 1888Died4 July 1964(1964-07-04) (aged 75)Allegiance Nazi GermanyService/branch German ArmyRankGeneral of the InfantryCommands255th Infantry DivisionV Army CorpsLXVI Reserve CorpsBattles/warsWorld War IIAwardsKnight's Cross of the Iron Cross Wilhelm Wetzel (17 July 1888 – 4 July 1964) was a general in the Wehrmacht of Nazi Germany during World War II. He was a recipient of the Knight's Cross of the Iron Cros...

 

La storia LGBT negli attuali Stati Uniti d'America ha il suo inizio nel periodo precedente alla colonizzazione europea delle Americhe. Indice 1 Pre-XX secolo 2 XVII-XIX secolo 3 1900-1965 4 1965-1999 4.1 Liberazione Gay 4.2 Migrazione Gay 4.3 Depenalizzazione nelle relazioni 4.4 Reazioni di opposizione 5 XXI secolo 6 Note 7 Voci correlate 8 Altri progetti 9 Collegamenti esterni Pre-XX secolo Tra le popolazioni e i gruppi dei nativi americani, sono sempre esistiti individui descritti come Two ...