Example usage for java.lang Double compare

List of usage examples for java.lang Double compare

Introduction

In this page you can find the example usage for java.lang Double compare.

Prototype

public static int compare(double d1, double d2) 

Source Link

Document

Compares the two specified double values.

Usage

From source file:playground.johannes.gsv.matrices.analysis.DumpRelations.java

private static List<Tuple<String, String>> getRelations(final KeyMatrix m) {
    //      Map<Double, Tuple<String, String>> map = new TreeMap<>(new Comparator<Double>() {
    ///*from   w w w . j  a va2s .c o  m*/
    //         @Override
    //         public int compare(Double o1, Double o2) {
    //            int result = -Double.compare(o1, o2);
    //            if (result == 0)
    //               return 1;// o1.hashCode() - o2.hashCode();
    //            else
    //               return result;
    //         }
    //      });
    //
    //      Set<String> keys = m.keys();
    //      for (String i : keys) {
    //         for (String j : keys) {
    //            Double val = m.get(i, j);
    //            if (val != null) {
    //               map.put(val, new Tuple<String, String>(i, j));
    //            }
    //         }
    //      }
    //
    //      List<Tuple<String, String>> list = new ArrayList<>(3000);
    //      int cnt = 0;
    //      for (Entry<Double, Tuple<String, String>> entry : map.entrySet()) {
    //         list.add(entry.getValue());
    //         cnt++;
    //         if (cnt > numRelations) {
    //            break;
    //         }
    //      }
    //
    //      return list;
    Set<Tuple<String, String>> set = new TreeSet<>(new Comparator<Tuple<String, String>>() {

        @Override
        public int compare(Tuple<String, String> o1, Tuple<String, String> o2) {
            Double val1 = m.get(o1.getFirst(), o1.getSecond());
            Double val2 = m.get(o2.getFirst(), o2.getSecond());

            if (val1 == null)
                val1 = 0.0;
            if (val2 == null)
                val2 = 0.0;

            int result = -Double.compare(val1, val2);
            if (result == 0) {
                double id1 = Double.parseDouble(o1.getFirst());
                double id2 = Double.parseDouble(o2.getFirst());
                return Double.compare(id1, id2);
            } else {
                return result;
            }

        }

    });

    Set<String> keys = m.keys();
    for (String i : keys) {
        for (String j : keys) {
            Double val = m.get(i, j);
            if (val != null) {
                set.add(new Tuple<String, String>(i, j));
            }
        }
    }

    List<Tuple<String, String>> list = new ArrayList<>(3000);
    int cnt = 0;
    for (Tuple<String, String> tuple : set) {
        list.add(tuple);
        cnt++;
        if (cnt >= numRelations) {
            break;
        }
    }

    return list;
}

From source file:cc.kave.commons.pointsto.evaluation.ProjectTrainValidateEvaluation.java

private List<List<ProjectIdentifier>> createProjectFolds(Set<ProjectIdentifier> projects, ICoReTypeName type,
        List<ProjectUsageStore> usageStores) throws IOException {
    Map<ProjectIdentifier, Double> numberOfUsages = new HashMap<>(projects.size());
    for (ProjectUsageStore store : usageStores) {
        Map<ProjectIdentifier, Integer> numberOfStoreUsages = store.getNumberOfUsagesPerProject(type);
        store.flush();//ww  w . ja  v  a 2 s  .  c o m
        for (Map.Entry<ProjectIdentifier, Integer> entry : numberOfStoreUsages.entrySet()) {
            double currentAverage = numberOfUsages.getOrDefault(entry.getKey(), 0.0);
            numberOfUsages.put(entry.getKey(), currentAverage + (1.0 / usageStores.size()) * entry.getValue());
        }
    }

    List<ProjectIdentifier> sortedProjects = new ArrayList<>(projects);
    sortedProjects.sort(new Comparator<ProjectIdentifier>() {

        @Override
        public int compare(ProjectIdentifier o1, ProjectIdentifier o2) {
            double avg1 = numberOfUsages.get(o1);
            double avg2 = numberOfUsages.get(o2);
            return Double.compare(avg1, avg2);
        }
    });

    return foldBuilder.createFolds(sortedProjects, numberOfUsages);
}

From source file:eu.hansolo.tilesfx.tools.Location.java

public boolean isZero() {
    return Double.compare(latitude, 0d) == 0 && Double.compare(longitude, 0d) == 0;
}

From source file:jasima.core.experiment.OCBAExperiment.java

private int[] findRank(final double[] means) {
    Integer[] idx = new Integer[means.length];
    for (int i = 0; i < idx.length; i++) {
        idx[i] = i;//  ww w . java  2  s.  com
    }

    Arrays.sort(idx, new Comparator<Integer>() {
        @Override
        public int compare(Integer i1, Integer i2) {
            return (getProblemType() == ProblemType.MAXIMIZE ? -1 : +1)
                    * Double.compare(means[i1.intValue()], means[i2.intValue()]);
        }
    });

    int[] ranks = new int[idx.length];
    for (int i = 0; i < ranks.length; i++) {
        ranks[idx[i].intValue()] = i + 1;
    }

    return ranks;
}

From source file:com.griddynamics.jagger.diagnostics.reporting.ProfileReporter.java

private void assembleTraceBack(MethodProfile pivot, Graph<MethodProfile, InvocationProfile> neighborhood,
        List<MethodElement> bag, int maxDepth, int depth) {
    bag.add(assembleMethodElement(pivot, depth));

    if (depth < maxDepth) {
        Collection<MethodProfile> callers = neighborhood.getPredecessors(pivot);

        if (callers != null) {
            List<MethodProfile> callersList = Lists.newArrayList(callers);
            Collections.sort(callersList, new Comparator<MethodProfile>() {
                @Override//w  w w.j  a v  a2  s.c  o  m
                public int compare(MethodProfile p1, MethodProfile p2) {
                    return -Double.compare(p1.getInStackRatio(), p2.getInStackRatio());
                }
            });

            for (MethodProfile caller : callersList) {
                assembleTraceBack(caller, neighborhood, bag, maxDepth, depth + 1);
            }
        }
    }
}

From source file:com.epam.cme.facades.bundle.impl.DefaultGuidedSellingFacade.java

protected Double getMinPriceOfRuleAndPlan(final SubscriptionPricePlanModel pricePlan,
        final ChangeProductPriceBundleRuleModel priceRule) {
    Double rulePrice = null;/*from w  w w .  j  ava  2  s.c  o  m*/
    Double planPrice = null;

    if (pricePlan != null) {
        final RecurringChargeEntryModel chargeEntry = getCommercePriceService()
                .getFirstRecurringPriceFromPlan(pricePlan);
        planPrice = chargeEntry.getPrice();
    }

    if (priceRule != null) {
        rulePrice = Double.valueOf(priceRule.getPrice().doubleValue());
    }

    if (rulePrice == null && planPrice != null) {
        return planPrice;
    } else if (rulePrice != null && planPrice == null) {
        return rulePrice;
    } else if (rulePrice != null && planPrice != null) {
        return (Double.compare(rulePrice.doubleValue(), planPrice.doubleValue()) == -1) ? rulePrice : planPrice;
    }

    return null;
}

From source file:com.thesmartweb.swebrank.DataManipulation.java

/**
 * Method that sorts a HashMap according to their values
 * @param map the HashMap to be sorted/*  w ww . j av  a 2 s  .  co m*/
 * @return a List that contains the keys in sorted (descending) fashion
 */
public List<String> sortHashmap(final HashMap<String, Double> map) {
    Set<String> set = map.keySet();
    List<String> keys = new ArrayList<String>(set);
    Collections.sort(keys, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return Double.compare(map.get(s2), map.get(s1));
        }
    });
    return keys;
}

From source file:com.spotify.helios.common.descriptors.HostInfo.java

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }//from w w  w. j av a 2  s  . c  om
    if (o == null || getClass() != o.getClass()) {
        return false;
    }

    final HostInfo hostInfo = (HostInfo) o;

    if (cpus != hostInfo.cpus) {
        return false;
    }
    if (Double.compare(hostInfo.loadAvg, loadAvg) != 0) {
        return false;
    }
    if (memoryTotalBytes != hostInfo.memoryTotalBytes) {
        return false;
    }
    if (memoryFreeBytes != hostInfo.memoryFreeBytes) {
        return false;
    }
    if (swapTotalBytes != hostInfo.swapTotalBytes) {
        return false;
    }
    if (swapFreeBytes != hostInfo.swapFreeBytes) {
        return false;
    }
    if (hostname != null ? !hostname.equals(hostInfo.hostname) : hostInfo.hostname != null) {
        return false;
    }
    if (uname != null ? !uname.equals(hostInfo.uname) : hostInfo.uname != null) {
        return false;
    }
    if (architecture != null ? !architecture.equals(hostInfo.architecture) : hostInfo.architecture != null) {
        return false;
    }
    if (osName != null ? !osName.equals(hostInfo.osName) : hostInfo.osName != null) {
        return false;
    }
    if (osVersion != null ? !osVersion.equals(hostInfo.osVersion) : hostInfo.osVersion != null) {
        return false;
    }
    if (dockerVersion != null ? !dockerVersion.equals(hostInfo.dockerVersion)
            : hostInfo.dockerVersion != null) {
        return false;
    }
    if (dockerHost != null ? !dockerHost.equals(hostInfo.dockerHost) : hostInfo.dockerHost != null) {
        return false;
    }
    return !(dockerCertPath != null ? !dockerCertPath.equals(hostInfo.dockerCertPath)
            : hostInfo.dockerCertPath != null);

}

From source file:eu.project.ttc.engines.morpho.CompostAE.java

@Override
public void collectionProcessComplete() throws AnalysisEngineProcessException {
    SubTaskObserver observer = observerResource.getTaskObserver(TASK_NAME);
    observer.setTotalTaskWork(termIndexResource.getTermIndex().getWords().size());
    LOGGER.info("Starting morphologyical compound detection for TermIndex {}",
            this.termIndexResource.getTermIndex().getName());
    LOGGER.debug(this.toString());
    wrMeasure = termIndexResource.getTermIndex().getWRMeasure();
    swtLemmaIndex = termIndexResource.getTermIndex().getCustomIndex(TermIndexes.SINGLE_WORD_LEMMA);
    buildCompostIndex();//w ww  .  j a  v a 2 s. co m

    final MutableLong cnt = new MutableLong(0);

    Timer progressLoggerTimer = new Timer("Morphosyntactic splitter AE");
    progressLoggerTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            int total = termIndexResource.getTermIndex().getWords().size();
            CompostAE.LOGGER.info("Progress: {}% ({} on {})",
                    String.format("%.2f", ((float) cnt.longValue() * 100) / total), cnt.longValue(), total);
        }
    }, 5000l, 5000l);

    int observingStep = 100;
    for (Term swt : termIndexResource.getTermIndex().getTerms()) {
        if (!swt.isSingleWord())
            continue;
        cnt.increment();
        if (cnt.longValue() % observingStep == 0) {
            observer.work(observingStep);
        }

        /*
         * Do not do native morphology splitting 
         * if a composition already exists.
         */
        Word word = swt.getWords().get(0).getWord();
        if (word.isCompound())
            continue;

        Map<Segmentation, Double> scores = computeScores(word.getLemma());
        if (scores.size() > 0) {

            List<Segmentation> segmentations = Lists.newArrayList(scores.keySet());

            /*
             *  compare segmentations in a deterministic way.
             */
            segmentations.sort(new Comparator<Segmentation>() {
                @Override
                public int compare(Segmentation o1, Segmentation o2) {
                    int comp = Double.compare(scores.get(o2), scores.get(o1));
                    if (comp != 0)
                        return comp;
                    comp = Integer.compare(o1.getSegments().size(), o2.getSegments().size());
                    if (comp != 0)
                        return comp;
                    for (int i = 0; i < o1.getSegments().size(); i++) {
                        comp = Integer.compare(o2.getSegments().get(i).getEnd(),
                                o1.getSegments().get(i).getEnd());
                        if (comp != 0)
                            return comp;
                    }
                    return 0;
                }
            });

            Segmentation bestSegmentation = segmentations.get(0);

            // build the word component from segmentation
            WordBuilder builder = new WordBuilder(word);

            for (Segment seg : bestSegmentation.getSegments()) {
                String lemma = segmentLemmaCache.getUnchecked(seg.getLemma());
                builder.addComponent(seg.getBegin(), seg.getEnd(), lemma);
                if (seg.isNeoclassical())
                    builder.setCompoundType(CompoundType.NEOCLASSICAL);
                else
                    builder.setCompoundType(CompoundType.NATIVE);
            }
            builder.create();

            // log the word composition
            if (LOGGER.isTraceEnabled()) {
                List<String> componentStrings = Lists.newArrayList();
                for (Component component : word.getComponents())
                    componentStrings.add(component.toString());
                LOGGER.trace("{} [{}]", word.getLemma(), Joiner.on(' ').join(componentStrings));
            }
        }
    }

    //finalize
    progressLoggerTimer.cancel();

    LOGGER.debug("segment score cache size: {}", segmentScoreEntries.size());
    LOGGER.debug("segment score hit count: " + segmentScoreEntries.stats().hitCount());
    LOGGER.debug("segment score hit rate: " + segmentScoreEntries.stats().hitRate());
    LOGGER.debug("segment score eviction count: " + segmentScoreEntries.stats().evictionCount());
    termIndexResource.getTermIndex().dropCustomIndex(TermIndexes.SINGLE_WORD_LEMMA);
    segmentScoreEntries.invalidateAll();
    segmentLemmaCache.invalidateAll();
}

From source file:io.cloudslang.content.utils.NumberUtilities.java

/**
 * Given an double string, it checks if it's a valid double (base on apaches NumberUtils.createDouble) and if
 * it's between the lowerBound and upperBound.
 *
 * @param doubleStr         the integer string to check
 * @param lowerBound        the lower bound of the interval
 * @param upperBound        the upper bound of the interval
 * @param includeLowerBound boolean if to include the lower bound of the interval
 * @param includeUpperBound boolean if to include the upper bound of the interval
 * @return true if the integer string is valid and in between the lowerBound and upperBound, false otherwise
 * @throws IllegalArgumentException if the lowerBound is not less than the upperBound
 *///w ww.  ja va  2s .c  om
public static boolean isValidDouble(@Nullable final String doubleStr, double lowerBound, double upperBound,
        final boolean includeLowerBound, final boolean includeUpperBound) {
    if (lowerBound > upperBound) {
        throw new IllegalArgumentException(ExceptionValues.INVALID_BOUNDS);
    } else if (!isValidDouble(doubleStr)) {
        return false;
    }
    final double aDouble = toDouble(doubleStr);
    final boolean respectsLowerBound = includeLowerBound ? Double.compare(lowerBound, aDouble) <= 0
            : lowerBound < aDouble;
    final boolean respectsUpperBound = includeUpperBound ? Double.compare(aDouble, upperBound) <= 0
            : aDouble < upperBound;
    return respectsLowerBound && respectsUpperBound;
}