For more general formula, see http://blog.smola.org/post/987977550/log-probabilities-semirings-and-floating-point-numbers
335902
public static double sumLogProbs(double probPos, double probNeg) {
        if (probPos > probNeg) {
            return probPos + Math.log(Math.exp(probNeg - probPos) + 1);
        } else {
            return probNeg + Math.log(Math.exp(probPos - probNeg) + 1);
        }
    }
19924
private static String getLeadingZeros(int i, int size)
	{
		assert i <= size;
		int w1 = (int) Math.floor(Math.log10(size));
		int w2 = (int) Math.floor(Math.log10(i));
		
		String s = "";

		for (int j = w2; j < w1; j++)
		{
			s += "0";
		}
		return s;
	}
1173575
public static double logcdf(double val, double shape1, double shape2) {
    if(val == Double.NEGATIVE_INFINITY) {
      return Double.NEGATIVE_INFINITY;
    }
    if(val == Double.POSITIVE_INFINITY) {
      return 0.;
    }
    if(val != val) {
      return Double.NaN;
    }
    if(shape1 == 0.) {
      val = FastMath.exp(-val);
    }
    else {
      double tmp = shape1 * val;
      if(tmp == Double.NEGATIVE_INFINITY) {
        return shape2 == 0 ? 0. : Double.NEGATIVE_INFINITY;
      }
      if(tmp >= 1.) {
        return shape2 == 0 ? Double.NEGATIVE_INFINITY : 0.;
      }
      val = FastMath.exp(FastMath.log1p(-tmp) / shape1);
    }
    if(shape2 == 0.) {
      return -val;
    }
    final double tmp = shape2 * val;
    return tmp < 1. ? FastMath.log1p(-tmp) / shape2 : Double.NEGATIVE_INFINITY;
  }
30807
private int getOthers(IMolecularFormula formula) {
        int number = 0;
        String[] elements = {"Co", "Hg", "Pt", "As"};
        for (int i = 0; i < elements.length; i++)
            number += MolecularFormulaManipulator.getElementCount(formula,
                    formula.getBuilder().newInstance(IElement.class, elements[i]));

        return number;
    }
1199331
private static void calculateClosure(Fst fst, State state, HashMap<Integer,Double>[] closure, Semiring semiring, int iEps, int oEps) {

    for (int j = 0; j < state.getArcCount(); j++) {
      Arc arc = state.getArc(j);
      if ((arc.getIlabel() != iEps) || (arc.getOlabel() != oEps)) {
        continue;
      }
      int nextStateId = arc.getNextState().getId();
      if (closure[nextStateId] == null) {
        calculateClosure(fst, arc.getNextState(), closure, semiring, iEps, oEps);
      }
      HashMap<Integer,Double> closureEntry = closure[nextStateId];
      if (closureEntry != null) {
        for (Integer pathFinalStateIndex : closureEntry.keySet()) {
          State pathFinalState = fst.getState(pathFinalStateIndex);
          Double prevPathWeight = getPathWeight(arc.getNextState(), pathFinalState, closure);
          Preconditions.checkNotNull(prevPathWeight, "prev arc %s never set in closure", arc);
          double newPathWeight = semiring.times(prevPathWeight, arc.getWeight());
          add(state, pathFinalState, newPathWeight, closure, semiring);
        }
      }
      add(state, arc.getNextState(), arc.getWeight(), closure, semiring);
    }
  }
1026534
function parseDecimal(x, str) {
    var e, i, len;

    // Decimal point?
    if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');

    // Exponential form?
    if ((i = str.search(/e/i)) > 0) {

      // Determine exponent.
      if (e < 0) e = i;
      e += +str.slice(i + 1);
      str = str.substring(0, i);
    } else if (e < 0) {

      // Integer.
      e = str.length;
    }

    // Determine leading zeros.
    for (i = 0; str.charCodeAt(i) === 48;) ++i;

    // Determine trailing zeros.
    for (len = str.length; str.charCodeAt(len - 1) === 48;) --len;
    str = str.slice(i, len);

    if (str) {
      len -= i;
      e = e - i - 1;
      x.e = mathfloor(e / LOG_BASE);
      x.d = [];

      // Transform base

      // e is the base 10 exponent.
      // i is where to slice str to get the first word of the digits array.
      i = (e + 1) % LOG_BASE;
      if (e < 0) i += LOG_BASE;

      if (i < len) {
        if (i) x.d.push(+str.slice(0, i));
        for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
        str = str.slice(i);
        i = LOG_BASE - str.length;
      } else {
        i -= len;
      }

      for (; i--;) str += '0';
      x.d.push(+str);

      if (external && (x.e > MAX_E || x.e < -MAX_E)) throw Error(exponentOutOfRange + e);
    } else {

      // Zero.
      x.s = 0;
      x.e = 0;
      x.d = [0];
    }

    return x;
  }
908397
function randProbPrime(k) {
  if (k>=600) return randProbPrimeRounds(k, 2); //numbers from HAC table 4.3
  if (k>=550) return randProbPrimeRounds(k, 4);
  if (k>=500) return randProbPrimeRounds(k, 5);
  if (k>=400) return randProbPrimeRounds(k, 6);
  if (k>=350) return randProbPrimeRounds(k, 7);
  if (k>=300) return randProbPrimeRounds(k, 9);
  if (k>=250) return randProbPrimeRounds(k, 12); //numbers from HAC table 4.4
  if (k>=200) return randProbPrimeRounds(k, 15);
  if (k>=150) return randProbPrimeRounds(k, 18);
  if (k>=100) return randProbPrimeRounds(k, 27);
              return randProbPrimeRounds(k, 40); //number from HAC remark 4.26 (only an estimate)
}
58464
function logProbs(prob, lowerTail, logp) {
         return logp ? lowerTail ? { p: prob, q: Math.log(-expm1(prob)) }
                                 : { p: Math.log(-expm1(prob)), q: prob }
                     : lowerTail ? { p: Math.log(prob), q: log1p(-prob) }
                                 : { p: log1p(-prob), q: Math.log(prob) };
      }
521912
double log_prob(char s1, int i1, char s2, int i2, char s3, int i3)
    {
        if (transMatrix[i1][i2][i3] == 0)
            return inf;
        char t1 = id2tag[i1];
        char t2 = id2tag[i2];
        char t3 = id2tag[i3];
        double uni = l1 * tf.freq(s3,t3);
        double bi = div(l2 * tf.get(s2,t2, s3,t3), tf.get(s2,t2));
        double tri = div(l3 * tf.get(s1,t1, s2,t2, s3,t3), tf.get(s1,t1, s2,t2));
        if (uni + bi + tri == 0)
            return inf;
        return Math.log(uni + bi + tri);
    }
1195638
def logsumexp(x):
    """"""
    max_x = np.max(x)
    return max_x + np.log(np.sum(np.exp(x - max_x)))
39803
def get_probability_grammar(self):
        
        # Creating valid word expression for probability, it is of the format
        # wor1 | var2 , var3 or var1 var2 var3 or simply var
        word_expr = Word(alphanums + '-' + '_') + Suppress(Optional("|")) + Suppress(Optional(","))
        word_expr2 = Word(initChars=printables, excludeChars=[',', ')', ' ', '(']) + Suppress(Optional(","))
        # creating an expression for valid numbers, of the format
        # 1.00 or 1 or 1.00. 0.00 or 9.8e-5 etc
        num_expr = Word(nums + '-' + '+' + 'e' + 'E' + '.') + Suppress(Optional(","))
        probability_expr = Suppress('probability') + Suppress('(') + OneOrMore(word_expr) + Suppress(')')
        optional_expr = Suppress('(') + OneOrMore(word_expr2) + Suppress(')')
        probab_attributes = optional_expr | Suppress('table')
        cpd_expr = probab_attributes + OneOrMore(num_expr)

        return probability_expr, cpd_expr
352889
function bup(a, b, x, y, n) {
      var logSeries;

      logSeries = Math.log(series(function(i, v) {
            if (i === 0) { return 1; }
            return v * x * (1 + (b - 1) / (a + i));
         }, n));
      return a * Math.log(x) + b * Math.log(y) - lbeta(a, b) - Math.log(a) +
         logSeries;
   }
816524
function calculateChiSquareProbability(x, df) {
    if (x <= 0.0 || df < 1)
        return 1.0;

    var a = 0.5 * x;

    if (df > 1)
        var y = calculateExponent(-a);

    var s = 2.0 * calculateNormalZProbability(-Math.sqrt(x));

    if (df > 2) {
        x = 0.5 * (df - 1.0);
        var z = 0.5;

        if (a > BIG_X) {
            var e = LOG_SQRT_PI;
            var c = Math.log(a);

            while (z <= x) {
                e = Math.log(z) + e;
                s += calculateExponent(c * z - a - e);
                z += 1.0;
            }

            return (s);
        }
        else {
            e = I_SQRT_PI / Math.sqrt(a);
            c = 0.0;

            while (z <= x) {
                e = e * (a / z);
                c = c + e;
                z += 1.0;
            }

            return (c * y + s);
        }
    }

    return s;
}
309994
private double logLikelihood(int[] contingencyTable) {
        // Rename for short-hand convenience
        int[] t = contingencyTable;
        int col1sum = t[0] + t[2];
        int col2sum = t[1] + t[3];
        int row1sum = t[0] + t[1];
        int row2sum = t[2] + t[3];
        double sum = row1sum + row2sum;
        
        // Calculate the expected values for a, b, c, d
        double aExp = (row1sum / sum) * col1sum;
        double bExp = (row1sum / sum) * col2sum;
        double cExp = (row2sum / sum) * col1sum;
        double dExp = (row2sum / sum) * col2sum;

        return 2 *
            ((t[0] * Math.log(t[0] - aExp))  +
             (t[1] * Math.log(t[1] - bExp))  +
             (t[2] * Math.log(t[2] - cExp))  +
             (t[3] * Math.log(t[3] - dExp)));
    }
1106370
def logsumexp(arr,axis=0):
    """"""
    minarr= numpy.amax(arr,axis=axis)
    if axis == 1:
        minarr= numpy.reshape(minarr,(arr.shape[0],1))
    if axis == 0:
        minminarr= numpy.tile(minarr,(arr.shape[0],1))
    elif axis == 1:
        minminarr= numpy.tile(minarr,(1,arr.shape[1]))
    elif axis == None:
        minminarr= numpy.tile(minarr,arr.shape)
    else:
        raise NotImplementedError("'galpy.util.logsumexp' not implemented for axis > 2")
    if axis == 1:
        minarr= numpy.reshape(minarr,(arr.shape[0]))
    return minarr+numpy.log(numpy.sum(numpy.exp(arr-minminarr),axis=axis))
441280
def _digits(minval, maxval):
    """"""
    if minval == maxval:
        return 3
    else:
        return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))
289479
private double getLogProductOfAllFalseMessages(VarTensor[] inMsgs) {
        // Precompute the product of all the "false" messages.
        // pi = \prod_i \mu_i(0)
        // Here we store log pi.
        Algebra s = inMsgs[0].getAlgebra();
        double logPi = 0.0;
        for (VarTensor inMsg : inMsgs) {
            logPi += s.toLogProb(inMsg.getValue(LinkVar.FALSE));
        }
        return logPi;
    }