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:org.talend.dataprep.schema.csv.SeparatorAnalyzerTest.java

@Test
public void should_perform_right_analysis() {
    // given//from   w w  w .  j  a  va 2 s.co  m
    final Separator semiColonSeparator = new Separator(';');
    semiColonSeparator.incrementCount(1);
    semiColonSeparator.incrementCount(2);
    final Separator commaSeparator = new Separator(';');
    commaSeparator.incrementCount(2);

    // when
    SeparatorAnalyzer separatorAnalyzer = new SeparatorAnalyzer(2, Arrays.asList("ID;Name", "1;Toto"));
    separatorAnalyzer.accept(semiColonSeparator);
    separatorAnalyzer.accept(commaSeparator);

    // then
    assertTrue(Double.compare(0.0, semiColonSeparator.getScore()) == 0);
    assertTrue(semiColonSeparator.isFirstLineAHeader());
    assertTrue(semiColonSeparator.isHeaderInfoReliable());
    String[] expectedHeaders = new String[] { "ID", "Name" };
    Object[] header = semiColonSeparator.getHeaders().stream().map(p -> p.getKey()).toArray();
    assertArrayEquals(expectedHeaders, header);

}

From source file:com.relicum.ipsum.Location.BlockPoint.java

@Override
public boolean equals(Object o) {
    if (this == o)
        return true;
    if (!(o instanceof BlockPoint))
        return false;

    BlockPoint that = (BlockPoint) o;/*from  w  ww . j av  a 2s  .  c om*/

    if (Double.compare(that.X, X) != 0)
        return false;
    if (Double.compare(that.Y, Y) != 0)
        return false;
    if (Double.compare(that.Z, Z) != 0)
        return false;
    if (!world.equals(that.world))
        return false;

    return true;
}

From source file:org.esa.s1tbx.insar.gpf.support.SARGeocoding.java

/**
 * Compute zero Doppler time for given earth point using bisection method.
 *
 * @param firstLineUTC     The zero Doppler time for the first range line.
 * @param lineTimeInterval The line time interval.
 * @param wavelength       The radar wavelength.
 * @param earthPoint       The earth point in xyz coordinate.
 * @param sensorPosition   Array of sensor positions for all range lines.
 * @param sensorVelocity   Array of sensor velocities for all range lines.
 * @return The zero Doppler time in days if it is found, -1 otherwise.
 * @throws OperatorException The operator exception.
 *///from w w  w .  ja  v  a 2  s.  c  o  m
public static double getEarthPointZeroDopplerTime(final double firstLineUTC, final double lineTimeInterval,
        final double wavelength, final PosVector earthPoint, final PosVector[] sensorPosition,
        final PosVector[] sensorVelocity) throws OperatorException {

    // binary search is used in finding the zero doppler time
    int lowerBound = 0;
    int upperBound = sensorPosition.length - 1;
    double lowerBoundFreq = getDopplerFrequency(earthPoint, sensorPosition[lowerBound],
            sensorVelocity[lowerBound], wavelength);
    double upperBoundFreq = getDopplerFrequency(earthPoint, sensorPosition[upperBound],
            sensorVelocity[upperBound], wavelength);

    if (Double.compare(lowerBoundFreq, 0.0) == 0) {
        return firstLineUTC + lowerBound * lineTimeInterval;
    } else if (Double.compare(upperBoundFreq, 0.0) == 0) {
        return firstLineUTC + upperBound * lineTimeInterval;
    } else if (lowerBoundFreq * upperBoundFreq > 0.0) {
        return NonValidZeroDopplerTime;
    }

    // start binary search
    double midFreq;
    while (upperBound - lowerBound > 1) {

        final int mid = (int) ((lowerBound + upperBound) / 2.0);
        midFreq = sensorVelocity[mid].x * (earthPoint.x - sensorPosition[mid].x)
                + sensorVelocity[mid].y * (earthPoint.y - sensorPosition[mid].y)
                + sensorVelocity[mid].z * (earthPoint.z - sensorPosition[mid].z);

        if (midFreq * lowerBoundFreq > 0.0) {
            lowerBound = mid;
            lowerBoundFreq = midFreq;
        } else if (midFreq * upperBoundFreq > 0.0) {
            upperBound = mid;
            upperBoundFreq = midFreq;
        } else if (Double.compare(midFreq, 0.0) == 0) {
            return firstLineUTC + mid * lineTimeInterval;
        }
    }

    final double y0 = lowerBound
            - lowerBoundFreq * (upperBound - lowerBound) / (upperBoundFreq - lowerBoundFreq);
    return firstLineUTC + y0 * lineTimeInterval;
}

From source file:com.bigml.histogram.Bin.java

public int compareTo(Bin o) {
    return Double.compare(getMean(), o.getMean());
}

From source file:it.units.malelab.sse.OperationsChromosome.java

@Override
public int compareTo(Chromosome another) {
    int fitnessComparison = -Double.compare(getFitness(), another.getFitness());
    int errorRatioComparison = -Double.compare(getStats().get(Evaluator.ResultType.ERROR_RATIO),
            ((OperationsChromosome) another).getStats().get(Evaluator.ResultType.ERROR_RATIO));
    int opsComparison = -Double.compare(getStats().get(Evaluator.ResultType.AVG_OPS),
            ((OperationsChromosome) another).getStats().get(Evaluator.ResultType.AVG_OPS));
    int sizeComparison = -Double.compare(getStats().get(Evaluator.ResultType.SIZE),
            ((OperationsChromosome) another).getStats().get(Evaluator.ResultType.SIZE));
    if (fitnessComparison != 0) {
        return fitnessComparison;
    }/*  www.  j  av a  2  s  .c  o  m*/
    if (errorRatioComparison != 0) {
        return errorRatioComparison;
    }
    if (opsComparison != 0) {
        return opsComparison;
    }
    return sizeComparison;
}

From source file:org.apache.mahout.knn.lsh.LocalitySensitiveHashTest.java

public void testSearch() throws Exception {
    int nVar = 10;
    final DistanceMeasure distance = new EuclideanDistanceMeasure();
    //WeightedEuclideanDistanceMeasure weightFunction = new WeightedEuclideanDistanceMeasure();
    //Vector w = new DenseVector(nVar);
    //w.assign(1);
    //w.viewPart(0, 5).assign(2);
    //w.viewPart(5, 5).assign(1);
    //weightFunction.setWeights(w);
    double d1 = 0;
    double d2 = 0;
    double d3 = 0;
    double t1 = 0;
    double t2 = 0;
    double t3 = 0;
    double tsim = 0.0;
    double sim;//from   ww w  .  ja  v  a2 s . com
    int nearest = 100;
    int numberOfNeighbors = 100;
    int sz;
    int tsz = 0;
    //LocalitySensitiveHash lsh = new LocalitySensitiveHash(weightFunction, nVar);
    LocalitySensitiveHash lsh = new LocalitySensitiveHash(distance, nVar, 2000);
    List<Vector> randomNeighbor = Lists.newArrayList();
    List<Vector> orgNeighbor = Lists.newArrayList();
    List<Vector> ref = Lists.newArrayList();
    //final DoubleFunction random = Functions.random();
    List<Vector> inputList = readInputFile("/Users/dixu/Documents/Amex/kNN/kMeansTestFile.csv");
    for (int i = 0; i < 40000; i++) {
        //Vector v = inputList.get(i);
        //v.assign(random);
        lsh.add(inputList.get(i), i);
        ref.add(inputList.get(i));
        orgNeighbor.add(inputList.get(i));
    }
    randomNeighbor.addAll(ref.subList(0, numberOfNeighbors));

    long runningTime = 0;
    for (int i = 40100; i < (40100 + nearest); i++) {
        final Vector v = inputList.get(i);
        //v.assign(random);
        long time1 = System.nanoTime();
        List<WeightedVector> rx = lsh.search(v, numberOfNeighbors);

        List<Vector> lshNeighbor = Lists.newArrayList();
        for (WeightedVector obs : rx) {
            lshNeighbor.add(obs.getVector());
        }
        long time2 = System.nanoTime();
        runningTime = runningTime + time2 - time1;

        sz = lsh.countVectors();

        Ordering<Vector> queryOrder = new Ordering<Vector>() {
            @Override
            public int compare(Vector v1, Vector v2) {
                return Double.compare(distance.distance(v, v1), distance.distance(v, v2));
            }
        };
        Collections.sort(orgNeighbor, queryOrder);
        List<Vector> trueNeighbor = orgNeighbor.subList(0, numberOfNeighbors);
        List<Vector> intersection1 = ListUtils.intersection(trueNeighbor, lshNeighbor);
        sim = intersection1.size() / (double) numberOfNeighbors;

        for (int j = 0; j < numberOfNeighbors; j++) {
            d1 += distance.distance(v, lshNeighbor.get(j));
            d2 += distance.distance(v, randomNeighbor.get(j));
            d3 += distance.distance(v, trueNeighbor.get(j));
        }
        d1 = d1 / numberOfNeighbors;
        d2 = d2 / numberOfNeighbors;
        d3 = d3 / numberOfNeighbors;
        t1 += d1;
        t2 += d2;
        t3 += d3;
        tsim += sim;
        tsz += sz;
    }
    t1 = t1 / nearest;
    t2 = t2 / nearest;
    t3 = t3 / nearest;
    tsim = tsim / nearest;
    tsz = tsz / nearest;
    System.out.printf("ave_search=%d ave_sim=%.2f trueNeighbor_dist=%.2f proxyNeighbor_dist=%.2f "
            + "randomNeighbor_dist=%.2f \n", tsz, tsim, t3, t1, t2);
    System.out.printf("running time = %.2f seconds \n", runningTime / 1e9);
}

From source file:eu.cloudwave.wp5.feedbackhandler.aggregations.strategies.RequestAggregationStrategyImpl.java

/**
 * {@inheritDoc}/*  w  w w  .  j  a  v  a2  s . co  m*/
 */
@Override
public RequestAggregationValues aggregate(RequestCollector requests) {
    double expectedCount = getExpectedNumberOfMeasurementValueGroups();

    /*
     * Group by aggregation interval and create summary statistics with min, avg, max and count
     */
    Collection<Long> groupedByAggregationInterval = requests.getReqTimestamps().stream()
            .collect(Collectors.groupingBy(
                    timestamp -> DateUtils.round(new Date(timestamp), timestampAggregation),
                    Collectors.counting()))
            .values();
    int calculatedCount = groupedByAggregationInterval.size();

    try {
        if (calculatedCount != 0) {
            // use integer summaryStatistics to get min, avg, max
            IntSummaryStatistics stats = groupedByAggregationInterval.stream().mapToInt(p -> toInt(p))
                    .summaryStatistics();

            // no time range selected, just return int summary
            if (expectedCount == 0) {
                return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(),
                        stats.getSum(), stats.getCount());
            } else {
                // if calculated count != expected count --> adjust minimum, average and count value
                if (Double.compare(calculatedCount, expectedCount) != 0) {
                    double newAverage = (double) (stats.getSum() / expectedCount);
                    return new RequestAggregationValuesImpl(0, stats.getMax(), newAverage, stats.getSum(),
                            (int) expectedCount);
                } else {
                    return new RequestAggregationValuesImpl(stats.getMin(), stats.getMax(), stats.getAverage(),
                            stats.getSum(), (int) expectedCount);
                }
            }
        } else {
            return new RequestAggregationValuesImpl(0, 0, 0, 0, 0);
        }
    } catch (ArithmeticException e) {
        System.out.println(e.getMessage());
        return new RequestAggregationValuesImpl(0, 0, 0, 0, 0);
    }
}

From source file:org.caleydo.neo4j.plugins.kshortestpaths.KShortestPathsAlgo.java

public List<WeightedPath> run(Node sourceNode, Node targetNode, int k, IPathReadyListener onPathReady) {
    StopWatch w = new StopWatch();
    w.start();/*from   ww w.  j ava2s . c  o m*/

    // Calculate shortest path first
    List<WeightedPath> paths = new ArrayList<>(k);
    profile("start", w);
    WeightedPath shortestPath = shortestPathFinder.findSinglePath(sourceNode, targetNode);
    if (shortestPath == null)
        return paths;
    profile("initial disjkra", w);
    PriorityQueue<WeightedPath> pathCandidates = new PriorityQueue<WeightedPath>(20,
            new Comparator<WeightedPath>() {
                @Override
                public int compare(WeightedPath o1, WeightedPath o2) {
                    return Double.compare(o1.weight(), o2.weight());
                }
            });

    Set<Integer> pathCandidateHashes = new HashSet<>();

    if (onPathReady != null) {
        onPathReady.onPathReady(shortestPath);
    }
    paths.add(shortestPath);

    pathCandidateHashes.add(generatePathHash(shortestPath));

    for (int i = 1; i < k; i++) {

        WeightedPath prevPath = paths.get(i - 1);

        for (Node spurNode : prevPath.nodes()) {
            if (spurNode.getId() == prevPath.endNode().getId())
                break;

            WeightedPath rootPath = getSubPathTo(prevPath, spurNode);

            for (Path path : paths) {
                Iterator<Relationship> pathIterator = path.relationships().iterator();
                boolean containsRootPath = true;

                // Test if the existing shortest path starts with the root path
                for (Relationship relationship : rootPath.relationships()) {
                    if (!pathIterator.hasNext()) {
                        containsRootPath = false;
                        break;
                    }

                    Relationship pathRelationship = pathIterator.next();
                    if (relationship.getId() != pathRelationship.getId()) {
                        containsRootPath = false;
                        break;
                    }
                }

                // If so, set edge weight of following edge in that path to infinity
                if (containsRootPath) {
                    if (pathIterator.hasNext()) {
                        Relationship r = pathIterator.next();
                        costEvaluator.addInvalidRelationship(r);
                        //profile("invalid: "+r,w);
                    }
                }
            }

            // Simulate removal of root path nodes (except spur node) by setting all their edge weights to
            // infinity
            Set<Long> badIds = new HashSet<Long>();
            for (Node rootPathNode : rootPath.nodes()) {
                if (rootPathNode.getId() != spurNode.getId()) {
                    badIds.add(rootPathNode.getId());
                    //for (Relationship relationship : getRelationships(rootPathNode)) {
                    //   costEvaluator.addInvalidRelationship(relationship);
                    //}
                    //profile("invalids: "+rootPathNode.getRelationships(),w);
                }
            }
            expander.setExtraIgnoreNodes(badIds);

            profile("Find next path", w);
            WeightedPath spurPath = shortestPathFinder.findSinglePath(spurNode, targetNode);
            profile("Found next path", w);
            if (spurPath != null && !Double.isInfinite(spurPath.weight())) {
                WeightedPath pathCandidate = concatenate(rootPath, spurPath);
                Integer pathHash = generatePathHash(pathCandidate);
                if (!pathCandidateHashes.contains(pathHash)) {
                    pathCandidates.add(pathCandidate);
                    pathCandidateHashes.add(pathHash);
                }
            }

            // Restore edges
            costEvaluator.clearInvalidRelationships();
            expander.setExtraIgnoreNodes(null);

        }

        if (pathCandidates.isEmpty())
            break;

        WeightedPath nextBest = pathCandidates.poll();
        profile("flush path", w);
        if (onPathReady != null) {
            onPathReady.onPathReady(nextBest);
        }
        paths.add(nextBest);

    }
    profile("done", w);
    return paths;
}

From source file:context.ui.control.tabular.TabularViewController.java

private void initialTableData() {
    data.loadTableData();/*from   ww  w. j a v a 2 s.  co  m*/
    //        double minWidth = tableView.getWidth() / data.getHeaders().size();
    tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    int index = 0;
    for (String header : data.getHeaders()) {
        final int j = index;
        TableColumn tableColumn = new TableColumn(header);

        tableColumn.setComparator(new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                if (NumberUtils.isNumber(s1) && NumberUtils.isNumber(s2)) {
                    return Double.compare(Double.parseDouble(s1), Double.parseDouble(s2));
                }
                return Collator.getInstance().compare(s1, s2);
            }
        });
        tableColumn.setCellValueFactory(
                new Callback<TableColumn.CellDataFeatures<List<String>, String>, ObservableValue<String>>() {
                    public ObservableValue<String> call(TableColumn.CellDataFeatures<List<String>, String> p) {
                        final String val = p.getValue().get(j);
                        if (isRoundDoubles() && NumberUtils.isNumber(val) && val.contains(".")) {
                            DecimalFormat df = new DecimalFormat("#.##");
                            Double d = Double.parseDouble(val);
                            return new SimpleStringProperty(df.format(d));
                        } else {
                            return new SimpleStringProperty(val);
                        }
                    }
                });
        index++;
        tableView.getColumns().add(tableColumn);
        //            if (index < data.getHeaders().size() - 1) {
        //                tableColumn.setMinWidth(minWidth);
        //            }
        //            System.out.println("width=" + tableColumn.getMinWidth());
    }
    System.out.println("columns Count:" + tableView.getColumns().size());
    //  which will make your table view dynamic 
    //        ObservableList<ObservableList> csvData = FXCollections.observableArrayList();
    //
    //        for (List<StringProperty> dataList : data.getRows()) {
    //            ObservableList<String> row = FXCollections.observableArrayList();
    //            for (StringProperty rowData : dataList) {
    //                row.add(rowData.get());
    //            }
    //            csvData.add(row); // add each row to cvsData
    //        }
    System.out.println("Rows Count=" + data.getRows().size());
    tableView.setItems(data.getRows()); // finally add data to tableview
    System.out.println("after Rows Count=" + tableView.getItems().size());

}

From source file:org.jberet.support.io.Company.java

@Override
public boolean equals(final Object o) {
    if (this == o)
        return true;
    if (!(o instanceof Company))
        return false;

    final Company company = (Company) o;

    if (Double.compare(company.lastSale, lastSale) != 0)
        return false;
    if (Double.compare(company.marketCap, marketCap) != 0)
        return false;
    if (address != null ? !address.equals(company.address) : company.address != null)
        return false;
    if (industry != null ? !industry.equals(company.industry) : company.industry != null)
        return false;
    if (ipoYear != null ? !ipoYear.equals(company.ipoYear) : company.ipoYear != null)
        return false;
    if (!name.equals(company.name))
        return false;
    if (sector != null ? !sector.equals(company.sector) : company.sector != null)
        return false;
    if (summaryQuote != null ? !summaryQuote.equals(company.summaryQuote) : company.summaryQuote != null)
        return false;
    if (!symbol.equals(company.symbol))
        return false;

    return true;// w w  w.  j ava  2  s.c  o m
}