[37] | 1 | function y = digamma(x) |
---|
| 2 | %DIGAMMA Digamma function. |
---|
| 3 | % DIGAMMA(X) returns digamma(x) = d log(gamma(x)) / dx |
---|
| 4 | % If X is a matrix, returns the digamma function evaluated at each element. |
---|
| 5 | |
---|
| 6 | % Reference: |
---|
| 7 | % |
---|
| 8 | % J Bernardo, |
---|
| 9 | % Psi ( Digamma ) Function, |
---|
| 10 | % Algorithm AS 103, |
---|
| 11 | % Applied Statistics, |
---|
| 12 | % Volume 25, Number 3, pages 315-317, 1976. |
---|
| 13 | % |
---|
| 14 | % From http://www.psc.edu/~burkardt/src/dirichlet/dirichlet.f |
---|
| 15 | |
---|
| 16 | large = 9.5; |
---|
| 17 | d1 = -0.5772156649015328606065121; % digamma(1) |
---|
| 18 | d2 = pi^2/6; |
---|
| 19 | small = 1e-6; |
---|
| 20 | s3 = 1/12; |
---|
| 21 | s4 = 1/120; |
---|
| 22 | s5 = 1/252; |
---|
| 23 | s6 = 1/240; |
---|
| 24 | s7 = 1/132; |
---|
| 25 | s8 = 691/32760; |
---|
| 26 | s9 = 1/12; |
---|
| 27 | s10 = 3617/8160; |
---|
| 28 | |
---|
| 29 | % Initialize |
---|
| 30 | y = zeros(size(x)); |
---|
| 31 | |
---|
| 32 | % illegal arguments |
---|
| 33 | i = find(x == -Inf | isnan(x)); |
---|
| 34 | if ~isempty(i) |
---|
| 35 | x(i) = NaN; |
---|
| 36 | y(i) = NaN; |
---|
| 37 | end |
---|
| 38 | |
---|
| 39 | % Negative values |
---|
| 40 | i = find(x < 0); |
---|
| 41 | if ~isempty(i) |
---|
| 42 | % Use the reflection formula (Jeffrey 11.1.6): |
---|
| 43 | % digamma(-x) = digamma(x+1) + pi*cot(pi*x) |
---|
| 44 | y(i) = digamma(-x(i)+1) + pi*cot(-pi*x(i)); |
---|
| 45 | % This is related to the identity |
---|
| 46 | % digamma(-x) = digamma(x+1) - digamma(z) + digamma(1-z) |
---|
| 47 | % where z is the fractional part of x |
---|
| 48 | % For example: |
---|
| 49 | % digamma(-3.1) = 1/3.1 + 1/2.1 + 1/1.1 + 1/0.1 + digamma(1-0.1) |
---|
| 50 | % = digamma(4.1) - digamma(0.1) + digamma(1-0.1) |
---|
| 51 | % Then we use |
---|
| 52 | % digamma(1-z) - digamma(z) = pi*cot(pi*z) |
---|
| 53 | end |
---|
| 54 | |
---|
| 55 | i = find(x == 0); |
---|
| 56 | if ~isempty(i) |
---|
| 57 | y(i) = -Inf; |
---|
| 58 | end |
---|
| 59 | |
---|
| 60 | % Use approximation if argument <= small. |
---|
| 61 | i = find(x > 0 & x <= small); |
---|
| 62 | if ~isempty(i) |
---|
| 63 | y(i) = y(i) + d1 - 1 ./ x(i) + d2*x(i); |
---|
| 64 | end |
---|
| 65 | |
---|
| 66 | % Reduce to digamma(X + N) where (X + N) >= large. |
---|
| 67 | while(1) |
---|
| 68 | i = find(x > small & x < large); |
---|
| 69 | if isempty(i) |
---|
| 70 | break |
---|
| 71 | end |
---|
| 72 | y(i) = y(i) - 1 ./ x(i); |
---|
| 73 | x(i) = x(i) + 1; |
---|
| 74 | end |
---|
| 75 | |
---|
| 76 | % Use de Moivre's expansion if argument >= large. |
---|
| 77 | % In maple: asympt(Psi(x), x); |
---|
| 78 | i = find(x >= large); |
---|
| 79 | if ~isempty(i) |
---|
| 80 | r = 1 ./ x(i); |
---|
| 81 | y(i) = y(i) + log(x(i)) - 0.5 * r; |
---|
| 82 | r = r .* r; |
---|
| 83 | y(i) = y(i) - r .* ( s3 - r .* ( s4 - r .* (s5 - r .* (s6 - r .* s7)))); |
---|
| 84 | end |
---|