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.esa.s1tbx.insar.gpf.support.SARGeocoding.java

/**
 * Compute zero Doppler time for given earth point using Newton's 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, NonValidZeroDopplerTime otherwise.
 * @throws OperatorException The operator exception.
 *///from w  w  w  .j a  v a 2  s .  c om
public static double getEarthPointZeroDopplerTimeNewton(final double firstLineUTC,
        final double lineTimeInterval, final double wavelength, final PosVector earthPoint,
        final PosVector[] sensorPosition, final PosVector[] sensorVelocity) throws OperatorException {
    final int lowerBound = 0;
    final int upperBound = sensorPosition.length - 1;
    final double lowerBoundFreq = getDopplerFrequency(earthPoint, sensorPosition[lowerBound],
            sensorVelocity[lowerBound], wavelength);
    final 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;
    }
    int yOld = 0, yOld1;
    int yNew = sensorPosition.length / 2, yNew1 = 0;
    final int yMax = sensorPosition.length - 1;
    double fOld = 0, fOld1 = 0, fNew = 0, fNew1 = 0, d = 0, y0;
    while (Math.abs(yNew - yOld) > 2) {
        yOld = yNew;
        yOld1 = yOld + 1;
        if (yOld1 > yMax) {
            yOld1 = yOld - 1;
        }
        fOld = getDopplerFrequency(earthPoint, sensorPosition[yOld], sensorVelocity[yOld], wavelength);
        fOld1 = getDopplerFrequency(earthPoint, sensorPosition[yOld1], sensorVelocity[yOld1], wavelength);
        d = (fOld1 - fOld) / (yOld1 - yOld);
        yNew = (int) (yOld - fOld / d);
        if (yNew < 0) {
            yNew = 0;
        } else if (yNew > yMax) {
            yNew = yMax;
        }
    }
    fNew = getDopplerFrequency(earthPoint, sensorPosition[yNew], sensorVelocity[yNew], wavelength);
    yNew1 = yNew + 1;
    fNew1 = getDopplerFrequency(earthPoint, sensorPosition[yNew1], sensorVelocity[yNew1], wavelength);
    if (fNew * fNew1 > 0.0) {
        yNew1 = yNew - 1;
        fNew1 = getDopplerFrequency(earthPoint, sensorPosition[yNew1], sensorVelocity[yNew1], wavelength);
    }
    y0 = yNew - fNew * (yNew1 - yNew) / (fNew1 - fNew);
    return firstLineUTC + y0 * lineTimeInterval;
}

From source file:eu.planets_project.pp.plato.evaluation.evaluators.ExperimentEvaluator.java

public Value evaluate(Alternative alternative, SampleObject sample, DigitalObject result,
        MeasurementInfoUri measurementInfoUri) {
    String propertyURI = measurementInfoUri.getAsURI();
    Scale scale = descriptor.getMeasurementScale(measurementInfoUri);
    if (scale == null) {
        // This means that I am not entitled to evaluate this measurementInfo and therefore supposed to skip it:
        return null;
    }/*from  www . j  a  va  2s .  com*/
    double sampleSize = sample.getData().getSize() * (1024 * 1024);

    if (OBJECT_ACTION_ACTIVITYLOGGING_AMOUNT.equals(propertyURI)) {
        Map<SampleObject, DetailedExperimentInfo> detailedInfo = alternative.getExperiment().getDetailedInfo();
        DetailedExperimentInfo detailedExperimentInfo = detailedInfo.get(sample);
        if ((detailedExperimentInfo != null) && (detailedExperimentInfo.getProgramOutput() != null)) {
            PositiveIntegerValue v = (PositiveIntegerValue) scale.createValue();
            v.setValue(detailedExperimentInfo.getProgramOutput().length());
            v.setComment("extracted from experiment details");
            return v;
        }
        return null;
    } else if (OBJECT_ACTION_ACTIVITYLOGGING_FORMAT.equals(propertyURI)) {
        Map<SampleObject, DetailedExperimentInfo> detailedInfo = alternative.getExperiment().getDetailedInfo();
        DetailedExperimentInfo detailedExperimentInfo = detailedInfo.get(sample);
        if ((detailedExperimentInfo != null) && (detailedExperimentInfo.getProgramOutput() != null)) {
            FreeStringValue v = (FreeStringValue) scale.createValue();
            v.setValue(evaluateLogging(detailedExperimentInfo.getProgramOutput()));
            v.setComment("extracted from experiments details");
            return v;
        }
        return null;
    } else if (OBJECT_ACTION_RUNTIME_PERFORMANCE_THROUGHPUT.equals(propertyURI)) {
        Value extracted = extractMeasuredValue(alternative, sample,
                OBJECT_ACTION_RUNTIME_PERFORMANCE_TIME_PERSAMPLE);
        if (extracted instanceof PositiveFloatValue) {
            PositiveFloatValue value = new PositiveFloatValue();
            double floatVal = ((PositiveFloatValue) extracted).getValue();
            if (Double.compare(floatVal, 0.0) != 0) {
                // calculate msec/MB
                floatVal = floatVal / sampleSize;
                // throughput is defined in MB per second, time/perMB is msec/MB
                value.setValue((1.0 / (floatVal / 1000.0)));
            }
            value.setComment("extracted from experiment details");
            return value;
        }
    } else if (OBJECT_ACTION_RUNTIME_PERFORMANCE_TIME_PERMB.equals(propertyURI)) {
        Value extracted = extractMeasuredValue(alternative, sample,
                OBJECT_ACTION_RUNTIME_PERFORMANCE_TIME_PERSAMPLE);
        if (extracted instanceof PositiveFloatValue) {
            PositiveFloatValue value = new PositiveFloatValue();
            double floatVal = ((PositiveFloatValue) extracted).getValue();
            if (Double.compare(floatVal, 0.0) != 0) {
                // calculate msec/MB
                floatVal = floatVal / sampleSize;
                value.setValue(floatVal);
            }
            value.setComment("extracted from experiment details");
            return value;
        }
    } else if (OBJECT_ACTION_RUNTIME_PERFORMANCE_MEMORY_PERMB.equals(propertyURI)) {
        Value extracted = extractMeasuredValue(alternative, sample,
                OBJECT_ACTION_RUNTIME_PERFORMANCE_MEMORY_PERSAMPLE);
        if (extracted instanceof PositiveFloatValue) {
            PositiveFloatValue value = new PositiveFloatValue();
            double floatVal = ((PositiveFloatValue) extracted).getValue();

            value.setValue(floatVal / sampleSize);
            value.setComment("extracted from experiment details");
            return value;
        }
    }
    Value extracted = extractMeasuredValue(alternative, sample, propertyURI);
    if (extracted != null) {
        extracted.setComment("extracted from experiment details");
    }
    return extracted;
}

From source file:org.stockchart.core.Axis.java

public Double[] getScaleValues(PaintInfo pinfo) {
    if (Double.compare(pinfo.Min, pinfo.Max) == 0)
        return null;

    if (null != this.getScaleValuesProvider())
        return this.getScaleValuesProvider().getScaleValues(pinfo, fLinesCount);

    double total = (pinfo.Max - pinfo.Min);
    double f = total / ((double) fLinesCount + 1);

    Double[] result = new Double[fLinesCount];

    double d = pinfo.Min + f;
    for (int k = 0; k < result.length; k++) {
        result[k] = d;/*from w  ww.ja  v a2 s.  c o  m*/
        d += f;
    }

    return result;
}

From source file:com.appleframework.monitor.model.MetricDog.java

/**
 * ??/* w  w  w .  j a v a2 s  . co  m*/
 *
 * @param metricValue
 * @return
 */
protected boolean bite(double metricValue) {
    if (StringUtils.equals("<", operator))
        return Double.compare(targetValue, metricValue) > 0;
    if (StringUtils.equals("=", operator))
        return Double.compare(targetValue, metricValue) == 0;
    if (StringUtils.equals(">", operator))
        return Double.compare(targetValue, metricValue) < 0;
    logger.warn("not support operator {} ,just support < , = , >", operator);
    return false;
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.CategoricalDist.java

/**
 * Sorts _objIdx and returns the reordered probabilities vector.
 * /*from   w w w .  j ava2s .  c o  m*/
 */
private double[] handleSort(double[] probs) {
    final Object[] mapKeys = _entriesToLogProbs.keys();
    /*
     * Sort the key index by key value, then reorder the prob value array with
     * sorted index.
     */
    Collections.sort(_objIdx, new Comparator<Integer>() {
        @SuppressWarnings("unchecked")
        @Override
        public int compare(Integer arg0, Integer arg1) {
            final T p0 = (T) mapKeys[arg0];
            final T p1 = (T) mapKeys[arg1];
            int probComp = Double.compare(_entriesToLogProbs.get(p0), _entriesToLogProbs.get(p1));
            if (probComp == 0)
                probComp = p0.compareTo(p1);
            return probComp;
        }
    });
    final double[] newProbs = new double[probs.length];
    for (int i = 0; i < probs.length; ++i) {
        newProbs[i] = probs[_objIdx.get(i)];
    }
    return newProbs;
}

From source file:com.joptimizer.algebra.CholeskyUpperDiagonalFactorization.java

/**
 * Cholesky factorization L of psd matrix, Q = L.LT.
 * Construction of the matrix L.//from  w ww . ja  v  a 2s .  c om
 */
public void factorize(boolean checkSymmetry) throws Exception {
    if (checkSymmetry && !Property.TWELVE.isSymmetric(Q)) {
        throw new Exception("Matrix is not symmetric");
    }

    if (this.rescaler != null) {
        double[] cn_00_original = null;
        double[] cn_2_original = null;
        double[] cn_00_scaled = null;
        double[] cn_2_scaled = null;
        if (log.isDebugEnabled()) {
            cn_00_original = ColtUtils.getConditionNumberRange(
                    new Array2DRowRealMatrix(ColtUtils.fillSubdiagonalSymmetricMatrix(Q).toArray()),
                    Integer.MAX_VALUE);
            log.debug("cn_00_original Q before scaling: " + ArrayUtils.toString(cn_00_original));
            cn_2_original = ColtUtils.getConditionNumberRange(
                    new Array2DRowRealMatrix(ColtUtils.fillSubdiagonalSymmetricMatrix(Q).toArray()), 2);
            log.debug("cn_2_original Q before scaling : " + ArrayUtils.toString(cn_2_original));
        }
        //scaling the Q matrix, we have:
        //Q1 = U.Q.U[T] = U.L.L[T].U[T] = (U.L).(U.L)[T] 
        //and because U is diagonal it preserves the triangular form of U.L, so
        //Q1 = U.Q.U[T] = L1.L1[T] is the new Cholesky decomposition  
        DoubleMatrix1D Uv = rescaler.getMatrixScalingFactorsSymm(Q);
        if (log.isDebugEnabled()) {
            boolean checkOK = rescaler.checkScaling(ColtUtils.fillSubdiagonalSymmetricMatrix(Q), Uv, Uv);
            if (!checkOK) {
                log.warn("Scaling failed (checkScaling = false)");
            }
        }
        this.U = Uv;
        this.Q = (SparseDoubleMatrix2D) ColtUtils.diagonalMatrixMult(Uv, Q, Uv);
        if (log.isDebugEnabled()) {
            cn_00_scaled = ColtUtils.getConditionNumberRange(
                    new Array2DRowRealMatrix(ColtUtils.fillSubdiagonalSymmetricMatrix(Q).toArray()),
                    Integer.MAX_VALUE);
            log.debug("cn_00_scaled Q after scaling : " + ArrayUtils.toString(cn_00_scaled));
            cn_2_scaled = ColtUtils.getConditionNumberRange(
                    new Array2DRowRealMatrix(ColtUtils.fillSubdiagonalSymmetricMatrix(Q).toArray()), 2);
            log.debug("cn_2_scaled Q after scaling  : " + ArrayUtils.toString(cn_2_scaled));

            if (cn_00_original[0] < cn_00_scaled[0] || cn_2_original[0] < cn_2_scaled[0]) {
                //log.info("Q: " + ArrayUtils.toString(ColtUtils.fillSubdiagonalSymmetricMatrix(Q).toArray()));
                log.warn("Problematic scaling");
                //throw new RuntimeException("Scaling failed");
            }
        }
    }

    double threshold = Utils.getDoubleMachineEpsilon();
    //elements of L are stored in a single array for i<diagonalLength, 
    //and with arrays of dimension i+1 for i>=diagonalLength
    this.LData = new double[dim - diagonalLength + 1][];
    double[] LData0 = new double[diagonalLength];
    LData[0] = LData0;

    if (dim - diagonalLength == 1 && Double.compare(Q.getQuick(dim - 1, dim - 1), 1.) == 0) {
        //TODO: the second condition can always be true if the matrix is normalized on the last element
        //closed form decomposition
        //@see "S.Boyd and L.Vandenberghe, Convex Optimization, p. 671"
        for (int i = 0; i < dim - 1; i++) {
            double d = Q.getQuick(i, i);
            if (d < Utils.getDoubleMachineEpsilon()) {
                throw new Exception("not positive definite matrix");
            }
            LData0[i] = Math.sqrt(d);
        }
        //now the last row of L
        double[] LData1 = new double[dim];
        for (int j = 0; j < dim - 1; j++) {
            LData1[j] = Q.getQuick(dim - 1, j) / LData0[j];
        }
        double d = 0;
        for (int k = 0; k < diagonalLength; k++) {
            d += Math.pow(Q.getQuick(dim - 1, k), 2) / Q.getQuick(k, k);
        }
        LData1[dim - 1] = Math.sqrt(1 - d);
        LData[1] = LData1;
    } else {
        for (int i = 0; i < dim; i++) {
            if (i < diagonalLength) {
                double d = Q.getQuick(i, i);
                if (!(d > threshold)) {
                    throw new Exception("not positive definite matrix");
                }
                LData0[i] = Math.sqrt(d);
            } else {

                LData[i - diagonalLength + 1] = new double[i + 1];
                double[] LDataI = LData[i - diagonalLength + 1];

                // j < i
                for (int j = 0; j < diagonalLength; j++) {
                    // here LData is not null only in its diagonal
                    LDataI[j] = 1.0 / LData[0][j] * (Q.getQuick(i, j));
                }
                for (int j = diagonalLength; j < i; j++) {
                    double[] LDataJ = LData[j - diagonalLength + 1];
                    double sum = 0.0;
                    for (int k = 0; k < j; k++) {
                        sum += LDataI[k] * LDataJ[k];
                    }
                    LDataI[j] = 1.0 / LDataJ[j] * (Q.getQuick(i, j) - sum);
                }
                // j==i
                double sum = 0.0;
                for (int k = 0; k < i; k++) {
                    sum += Math.pow(LDataI[k], 2);
                }
                double d = Q.getQuick(i, i) - sum;
                if (d < Utils.getDoubleMachineEpsilon()) {
                    throw new Exception("not positive definite matrix");
                }
                LDataI[i] = Math.sqrt(d);
            }
        }
    }
}

From source file:eu.crisis_economics.abm.markets.clearing.heterogeneous.ClearingGiltsBondsAndCommercialLoansMarket.java

/**
  * Assign commerical loan consumers to risk grades according
  * to their equity. In this implementation, the number of 
  * consumer assigned to each bucket is approximately equal.
  *///from w w  w.j ava 2s .  co  m
private void assignCommericalLoanClientsToRiskBuckets() {
    final int numRiskBuckets = commercialLoanRiskGrades.size();
    final List<ClearingMarketParticipant> firms = getAllPossibleCommericalLoanConsumers();

    class SortedEquityID implements Comparable<SortedEquityID> {
        private double equity;
        private ClearingMarketParticipant firm;

        SortedEquityID(final double equity, final ClearingMarketParticipant firm) {
            this.equity = equity;
            this.firm = firm;
        }

        @Override
        public int compareTo(SortedEquityID other) {
            return Double.compare(this.equity, other.equity);
        }
    }

    final TreeMultiset<SortedEquityID> firmEquities = TreeMultiset.create();
    for (final ClearingMarketParticipant participant : firms) {
        final LoanStrategyFirm firm = (LoanStrategyFirm) participant; // Contracted by ClearingHouse
        firmEquities.add(new SortedEquityID(firm.getEquity(), participant));
    }
    final int numFirms = firms.size(),
            firmsPerRiskBucket = (int) Math.floor(numFirms / (double) numRiskBuckets);
    int firmCounter = 0, riskGradeIndex = 0;
    String riskGrade = commercialLoanRiskGrades.get(0);
    for (final SortedEquityID record : firmEquities) {
        commericalLoanClientRiskBuckets.get(riskGrade).add(record.firm);
        ++firmCounter;
        if (firmCounter == firmsPerRiskBucket && !(riskGradeIndex == numRiskBuckets - 1)) {
            firmCounter = 0;
            ++riskGradeIndex;
            riskGrade = commercialLoanRiskGrades.get(riskGradeIndex);
        }
    }
    return;
}

From source file:com.github.steveash.jg2p.align.Alignment.java

@Override
public int compareTo(Alignment that) {
    return Double.compare(this.score, that.score);
}

From source file:com.opengamma.analytics.financial.interestrate.payments.derivative.CouponCMS.java

@Override
public boolean equals(final Object obj) {
    if (this == obj) {
        return true;
    }// w  ww.j  a va  2  s  . c o m
    if (!super.equals(obj)) {
        return false;
    }
    if (!(obj instanceof CouponCMS)) {
        return false;
    }
    final CouponCMS other = (CouponCMS) obj;
    if (Double.compare(_settlementTime, other._settlementTime) != 0) {
        return false;
    }
    if (!ObjectUtils.equals(_underlyingSwap, other._underlyingSwap)) {
        return false;
    }
    return true;
}

From source file:com.inform.jamps.solver.gurobi.GurobiExpression.java

@Override
public int compareTo(final Expression expr) {
    if (!(expr instanceof GurobiExpression)) {
        return -1;
    }//ww  w.j  a  va  2s  .c o  m
    if (equals(expr)) {
        return 0;
    }

    final GurobiExpression grbExpr = ((GurobiExpression) expr);
    final int exprLength1 = linearTerms.size() + (Precision.equals(constant, ZERO_COEFFICIENT) ? 0 : 1);
    final int exprLength2 = grbExpr.linearTerms.size()
            + (Precision.equals(grbExpr.constant, ZERO_COEFFICIENT) ? 0 : 1);

    final int result = Integer.valueOf(exprLength1).compareTo(exprLength2);
    if (result != 0) {
        return result;
    }

    return Double.compare(constant, grbExpr.constant);
}