aherbert commented on code in PR #353:
URL: https://github.com/apache/commons-math/pull/353#discussion_r4532216303


##########
commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/distribution/EnumeratedRealDistribution.java:
##########
@@ -158,7 +158,9 @@ public double inverseCumulativeProbability(final double p) 
throws OutOfRangeExce
 
         double probability = 0;
         double x = getSupportLowerBound();
-        for (final Pair<Double, Double> sample : innerDistribution.getPmf()) {
+        final List<Pair<Double, Double>> samples = innerDistribution.getPmf();
+        samples.sort((a, b) -> Double.compare(a.getKey(), b.getKey()));

Review Comment:
   Sorting the PMF on each call to `inverseCumulativeProbability` is a large 
performance overhead. The sorted list should be computed once.
   
   The innerDistribution is private and constructed by iterating over a Map of 
value -> count pairs. This is a LinkedHashMap. If this is changed to TreeMap 
then the inner distribution will be created with a sorted set of values. This 
fixes the case where the values constructor is called (equal weights).
   
   ```java
       public EnumeratedRealDistribution(final double[] data) {
           final Map<Double, Integer> dataMap = new TreeMap<>();
           // ...
   ```
   
   For the other case (values and counts), the List of samples can be sorted:
   ```java
   public EnumeratedRealDistribution(final double[] singletons,
                                     final double[] probabilities)
      throws /* lots of exceptions */ {
           final List<Pair<Double, Double>> samples = 
createDistribution(singletons, probabilities);
           samples.sort(Comparator.comparingDouble(Pair::getKey));
           innerDistribution = new EnumeratedDistribution<>(samples);
   }
   ```
   The modifications above fix your new tests.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to