gonum.org/v1/gonum@v0.14.0/mathext/digamma.go (about) 1 // Copyright ©2016 The Gonum Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package mathext 6 7 import ( 8 "math" 9 ) 10 11 // Digamma returns the logorithmic derivative of the gamma function at x. 12 // 13 // ψ(x) = d/dx (Ln (Γ(x)). 14 func Digamma(x float64) float64 { 15 // This is adapted from 16 // http://web.science.mq.edu.au/~mjohnson/code/digamma.c 17 var result float64 18 switch { 19 case math.IsNaN(x), math.IsInf(x, 1): 20 return x 21 case math.IsInf(x, -1): 22 return math.NaN() 23 case x == 0: 24 return math.Copysign(math.Inf(1), -x) 25 case x < 0: 26 if x == math.Floor(x) { 27 return math.NaN() 28 } 29 // Reflection formula, http://dlmf.nist.gov/5.5#E4 30 _, r := math.Modf(x) 31 result = -math.Pi / math.Tan(math.Pi*r) 32 x = 1 - x 33 } 34 for ; x < 7; x++ { 35 // Recurrence relation, http://dlmf.nist.gov/5.5#E2 36 result -= 1 / x 37 } 38 x -= 0.5 39 xx := 1 / x 40 xx2 := xx * xx 41 xx4 := xx2 * xx2 42 // Asymptotic expansion, http://dlmf.nist.gov/5.11#E2 43 result += math.Log(x) + (1.0/24.0)*xx2 - (7.0/960.0)*xx4 + (31.0/8064.0)*xx4*xx2 - (127.0/30720.0)*xx4*xx4 44 return result 45 }