/** * Computes \log(\sum_{i=1}^n e^{x_i}) using a maximum-element trick * to avoid arithmetic overflow. * * @param x input vector * @return log-sum of exponentials of vector elements */ public static double logSumOfExps(double[] x) { double max = max(x); double sum = 0.0; for (int i = 0; i < x.length; i++) { if (x[i] != Double.NEGATIVE_INFINITY) sum += Math.exp(x[i] - max); } return max + Math.log(sum); }