| 34 | /** |
| 35 | */ |
| 36 | public final class MathUtils { |
| 37 | |
| 38 | /** The natural logarithm of 10 */ |
| 39 | public static final double LOG_10 = Math.log(10.0); |
| 40 | /** The natural logarithm of 2 */ |
| 41 | public static final double LOG_2 = Math.log(2); |
| 42 | /** The natural logarithm of e */ |
| 43 | public static final double LOG10_E = Math.log10(Math.E); |
| 44 | |
| 45 | private MathUtils() { //prevent instantiation |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Compute -log of a binomial of form p^n*(1-p)^(N-n)binomial(N,n). |
| 50 | * |
| 51 | * @param p probability |
| 52 | * @param nn total population |
| 53 | * @param n marked subpopulation |
| 54 | * @return -log of a binomial of form p^n*(1-p)^(N-n)binomial(N,n) |
| 55 | */ |
| 56 | public static double logBinomial(final double p, final int nn, final int n) { |
| 57 | assert p >= 0.0 && p <= 1.0; |
| 58 | assert n >= 0; |
| 59 | assert nn >= 0; |
| 60 | final int m = nn - n; |
| 61 | if (p == 0.0) { |
| 62 | if (n == 0) { |
| 63 | return 0.0; |
| 64 | } |
| 65 | throw new IllegalArgumentException("if probability is 0.0 then count must be 0. p:" + p |
| 66 | + " N:" + nn + " n:" + n); |
| 67 | } |
| 68 | if (p == 1.0) { |
| 69 | if (m == 0) { |
| 70 | return 0.0; |
| 71 | } |
| 72 | throw new IllegalArgumentException("if probability is 1.0 then count must be 0. p:" + p |
| 73 | + " N:" + nn + " n:" + n); |
| 74 | } |
| 75 | final double res = n * Math.log(p) + m * Math.log(1.0f - p) + logBinomial(nn, n); |
| 76 | assert res <= 0; |
| 77 | return -res; |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * Compute log binomial(N,n). |
| 82 | * |
| 83 | * @param nn total count. |
| 84 | * @param n subset count. |
| 85 | * @return log binomial(N,n) |
| 86 | */ |
| 87 | public static double logBinomial(final int nn, final int n) { |
| 88 | assert n >= 0; |
| 89 | assert nn >= n; |
| 90 | if (nn <= 1 || n == 0 || n == nn) { |
| 91 | return 0.0; |
| 92 | } |
| 93 | if (n == 1 || n == (nn - 1)) { |