| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
package dr.math.functionEval; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
public final class GammaFunction |
| 34 |
{ |
| 35 |
static double sqrt2Pi = Math.sqrt( 2 * Math.PI); |
| 36 |
static double[] coefficients = { 76.18009172947146, |
| 37 |
-86.50532032941677, |
| 38 |
24.01409824083091, |
| 39 |
-1.231739572450155, |
| 40 |
0.1208650973866179e-2, |
| 41 |
-0.5395239384953e-5}; |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
public static double beta ( double x, double y) |
| 49 |
{ |
| 50 |
return Math.exp( logGamma( x) + logGamma( y) - logGamma( x + y)); |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
public static long factorial ( long n) |
| 57 |
{ |
| 58 |
return n < 2 ? 1 : n * factorial( n - 1); |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
public static double gamma ( double x) |
| 65 |
{ |
| 66 |
return x > 1 |
| 67 |
? Math.exp( leadingFactor(x)) * series(x) * sqrt2Pi / x |
| 68 |
: ( x > 0 ? gamma(x + 1) / x |
| 69 |
: Double.NaN); |
| 70 |
} |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
private static double leadingFactor ( double x) |
| 76 |
{ |
| 77 |
double temp = x + 5.5; |
| 78 |
return Math.log( temp) * ( x + 0.5) - temp; |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
public static double logBeta ( double x, double y) |
| 86 |
{ |
| 87 |
return logGamma( x) + logGamma( y) - logGamma( x + y); |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
public static double logGamma ( double x) |
| 94 |
{ |
| 95 |
return x > 1 |
| 96 |
? leadingFactor(x) + Math.log( series(x) * sqrt2Pi / x) |
| 97 |
: ( x > 0 ? logGamma(x + 1) - Math.log( x) |
| 98 |
: Double.NaN); |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
private static double series( double x) |
| 105 |
{ |
| 106 |
double answer = 1.000000000190015; |
| 107 |
double term = x; |
| 108 |
for ( int i = 0; i < 6; i++) |
| 109 |
{ |
| 110 |
term += 1; |
| 111 |
answer += coefficients[i] / term; |
| 112 |
} |
| 113 |
return answer; |
| 114 |
} |
| 115 |
} |