private void normalizeLogArr ( double [ ] arr ) { // Find the log-scale normalization value double max = Double . NEGATIVE_INFINITY ; for ( double d : arr ) { if ( d > max ) max = d ; } double expSum = 0.0 ; for ( double d : arr ) { expSum += Math . exp ( d - max ) ; } double logSumExp = max + Math . log ( expSum ) ; if ( Double . isInfinite ( logSumExp ) ) { // Just put in uniform probabilities if we are normalizing all 0s for ( int i = 0 ; i < arr . length ; i ++ ) { arr [ i ] = 1.0 / arr . length ; } } else { // Normalize in log-scale before exponentiation, to help with stability for ( int i = 0 ; i < arr . length ; i ++ ) { arr [ i ] = Math . exp ( arr [ i ] - logSumExp ) ; } } }
Super basic in - place array normalization