| 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; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
public class LogTricks { |
| 32 |
|
| 33 |
public static final double maxFloat = Double.MAX_VALUE; |
| 34 |
public static final double logLimit = -maxFloat / 100; |
| 35 |
public static final double logZero = -maxFloat; |
| 36 |
public static final double NATS = 400; |
| 37 |
|
| 38 |
public static double logSumNoCheck(double x, double y) { |
| 39 |
double temp = y - x; |
| 40 |
if (Math.abs(temp) > NATS) |
| 41 |
return (x > y) ? x : y; |
| 42 |
else |
| 43 |
return x + StrictMath.log1p(StrictMath.exp(temp)); |
| 44 |
} |
| 45 |
|
| 46 |
public static double logSum(double[] x) { |
| 47 |
double sum = x[0]; |
| 48 |
final int len = x.length; |
| 49 |
for(int i=1; i<len; i++) |
| 50 |
sum = logSumNoCheck(sum,x[i]); |
| 51 |
return sum; |
| 52 |
} |
| 53 |
|
| 54 |
public static double logSum(double x, double y) { |
| 55 |
final double temp = y - x; |
| 56 |
if (temp > NATS || x < logLimit) |
| 57 |
return y; |
| 58 |
if (temp < -NATS || y < logLimit) |
| 59 |
return x; |
| 60 |
if (temp < 0) |
| 61 |
return x + StrictMath.log1p(StrictMath.exp(temp)); |
| 62 |
return y + StrictMath.log1p(StrictMath.exp(-temp)); |
| 63 |
} |
| 64 |
|
| 65 |
public static void logInc(Double x, double y) { |
| 66 |
double temp = y - x; |
| 67 |
if (temp > NATS || x < logLimit) |
| 68 |
x = y; |
| 69 |
else if (temp < -NATS || y < logLimit) |
| 70 |
; |
| 71 |
else |
| 72 |
x += StrictMath.log1p(StrictMath.exp(temp)); |
| 73 |
} |
| 74 |
|
| 75 |
public static double logDiff(double x, double y) { |
| 76 |
assert x > y; |
| 77 |
double temp = y - x; |
| 78 |
if (temp < -NATS || y < logLimit) |
| 79 |
return x; |
| 80 |
return x + StrictMath.log1p(-Math.exp(temp)); |
| 81 |
} |
| 82 |
|
| 83 |
} |