Debian Codegraph @

src/dr/math/LogTricks.java

raw symbols SCIP
1 /*
2 * LogTricks.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.math;
27
28 /**
29 * @author Marc Suchard
30 */
31 public class LogTricks {
32
33 public static final double maxFloat = Double.MAX_VALUE; //3.40282347E+38;
34 public static final double logLimit = -maxFloat / 100;
35 public static final double logZero = -maxFloat;
36 public static final double NATS = 400; //40;
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 }