Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

In this page you can find the example usage for java.math BigDecimal compareTo.

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:de.iteratec.iteraplan.elasticeam.operator.rangify.Range.java

public Range(String name, BigDecimal lowerBound, BigDecimal upperBound) {

    if (lowerBound == null || upperBound == null || lowerBound.compareTo(NEGATIVE_INFINITY) == -1
            || upperBound.compareTo(POSITIVE_INFINITY) == 1 || lowerBound.compareTo(upperBound) == 1) {
        throw new ModelException(ModelException.INCONSISTENT_RANGES,
                "The range you have provided is inconsistent. Are both bounds not null and between neagtive and positive infinity?");
    }//  ww w .  ja v  a  2  s  .c om
    this.name = name;
    this.lowerBound = lowerBound;
    this.upperBound = upperBound;
}

From source file:org.eel.kitchen.jsonschema.keyword.MaximumKeywordValidator.java

@Override
protected void validateDecimal(final ValidationReport report, final JsonNode instance) {
    final BigDecimal instanceValue = instance.decimalValue();
    final BigDecimal decimalValue = number.decimalValue();

    final int cmp = instanceValue.compareTo(decimalValue);

    if (cmp < 0)
        return;//from  ww  w  .  j a  va2 s.c  om

    final Message.Builder msg = newMsg().addInfo(keyword, number).addInfo("found", instance);

    if (cmp > 0) {
        msg.setMessage("number is greater than the required maximum");
        report.addMessage(msg.build());
        return;
    }

    if (!exclusive)
        return;

    msg.setMessage("number is not strictly lower than the required maximum").addInfo("exclusiveMaximum",
            nodeFactory.booleanNode(true));
    report.addMessage(msg.build());
}

From source file:py.una.pol.karaku.test.test.math.QuantityTest.java

private void assertQuantity(Quantity actual, BigDecimal bd) {

    int result = bd.compareTo(actual.bigDecimalValue());
    if (result != 0) {
        throw new ComparisonFailure("", actual.toString(), bd.toString());
    }//www. j a v a 2  s .co m
}

From source file:org.maodian.flyingcat.xmpp.state.StreamState.java

private void doHandle(XmppContext context, XMLStreamReader xmlsr, XMLStreamWriter xmlsw)
        throws XMLStreamException {
    xmlsr.nextTag();//from  w  w  w.  ja v  a 2  s. c  om
    QName qname = new QName(XmppNamespace.STREAM, "stream");
    if (!xmlsr.getName().equals(qname)) {
        throw new XmppException(StreamError.INVALID_NAMESPACE).set("QName", xmlsr.getName());
    }

    // throw exception if client version > 1.0
    BigDecimal version = new BigDecimal(xmlsr.getAttributeValue("", "version"));
    if (version.compareTo(SUPPORTED_VERSION) > 0) {
        throw new XmppException(StreamError.UNSUPPORTED_VERSION);
    }

    xmlsw.writeStartDocument();
    xmlsw.writeStartElement("stream", "stream", XmppNamespace.STREAM);
    xmlsw.writeNamespace("stream", XmppNamespace.STREAM);
    xmlsw.writeDefaultNamespace(XmppNamespace.CLIENT_CONTENT);

    xmlsw.writeAttribute("id", RandomStringUtils.randomAlphabetic(32));
    xmlsw.writeAttribute("version", "1.0");
    xmlsw.writeAttribute("from", "localhost");
    xmlsw.writeAttribute(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI, "lang", "en");
    String from = xmlsr.getAttributeValue(null, "from");
    if (from != null) {
        xmlsw.writeAttribute("to", from);
    }

    // features
    xmlsw.writeStartElement(XmppNamespace.STREAM, "features");
    writeFeatures(xmlsw);
    xmlsw.writeEndElement();
}

From source file:io.silverware.microservices.monitoring.MetricsManager.java

/**
 * Method responsible for adding new time to values collection and also updating min, max, avg and count metrics.
 *
 * @param elapsedTime/*from  w w w . j a v  a  2  s  .  c o  m*/
 *       runtime of microservice method.
 */
public void addTime(BigDecimal elapsedTime) {

    if (elapsedTime.compareTo(BigDecimal.ZERO) <= 0) {
        throw new IllegalArgumentException("Elapsed time is negative or zero");
    }

    mapValues.put(longAdder.longValue(), elapsedTime);

    longAdder.increment();

    final BigDecimal count = new BigDecimal(metrics.getCount());
    final BigDecimal averageTime = metrics.getAverageTime();
    final BigDecimal minTime = metrics.getMinTime();
    final BigDecimal maxTime = metrics.getMaxTime();

    metrics.incrementCount();

    metrics.setAverageTime((averageTime.multiply(count).add(elapsedTime)).divide(count.add(BigDecimal.ONE),
            BigDecimal.ROUND_HALF_UP));

    if (elapsedTime.compareTo(maxTime) >= 1) {
        metrics.setMaxTime(elapsedTime);
    } else {
        metrics.setMinTime(elapsedTime);
    }
}

From source file:model.experiments.stickyprices.StickyPricesCSVPrinter.java

private static void woodMonopolistSweep(final BigDecimal minimumP, final BigDecimal maximumP,
        final BigDecimal minimumI, final BigDecimal maximumI, final BigDecimal increment,
        final int runsPerParameterCombination) throws IOException {

    CSVWriter writer = new CSVWriter(new FileWriter(Paths.get("runs", "rawdata", "monoSweep.csv").toFile()));
    writer.writeNext(new String[] { "P", "I", "distance", "variance", "success" });

    BigDecimal currentP = minimumP;
    while (currentP.compareTo(maximumP) <= 0) {
        BigDecimal currentI = minimumI;

        while (currentI.compareTo(maximumI) <= 0) {

            SummaryStatistics averageSquaredDistance = new SummaryStatistics();
            SummaryStatistics averageVariance = new SummaryStatistics();
            int successes = 0;

            for (int run = 0; run < runsPerParameterCombination; run++) {

                //create the run
                MacroII macroII = new MacroII(run);
                MonopolistScenario scenario = new MonopolistScenario(macroII);
                macroII.setScenario(scenario);
                //set the demand
                scenario.setDemandIntercept(102);
                scenario.setDemandSlope(2);
                scenario.setDailyWageSlope(1);
                scenario.setDailyWageIntercept(0);
                scenario.setAskPricingStrategy(SimpleFlowSellerPID.class);
                scenario.setWorkersToBeRehiredEveryDay(true);
                scenario.setControlType(
                        MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL);
                scenario.setBuyerDelay(0);

                //start it and have one step
                macroII.start();//from w  w  w  . j  a  v  a  2 s .  c  om
                macroII.schedule.step(macroII);

                //now set the right parameters
                final SalesDepartment salesDepartment = scenario.getMonopolist()
                        .getSalesDepartment(UndifferentiatedGoodType.GENERIC);
                final SimpleFlowSellerPID strategy = new SimpleFlowSellerPID(salesDepartment,
                        currentP.floatValue(), currentI.floatValue(), 0f, 0, salesDepartment.getMarket(),
                        salesDepartment.getRandom().nextInt(100), salesDepartment.getFirm().getModel());
                //  strategy.setInitialPrice(102);
                //start them all at the same price, otherwise you advantage the slow by being so slow initially that they end up being right later

                salesDepartment.setAskPricingStrategy(strategy);

                //and make it learned!
                salesDepartment.setPredictorStrategy(new FixedDecreaseSalesPredictor(2));
                final HumanResources hr = scenario.getMonopolist().getHRs().iterator().next();
                hr.setPredictor(new FixedIncreasePurchasesPredictor(1));

                float totalDistance = 0;
                SummaryStatistics prices = new SummaryStatistics();
                //run the model
                double price = 0;
                double quantity = 0;
                for (int i = 0; i < 1000; i++) {
                    macroII.schedule.step(macroII);
                    price = strategy.getTargetPrice();
                    quantity = salesDepartment.getTodayInflow();
                    totalDistance += Math
                            .pow(Math.min(price - (102 - 2 * quantity), price - (102 - 2 * quantity - 1)), 2);
                    prices.addValue(price);
                }

                //Model over, now compute statistics

                averageSquaredDistance.addValue(Math.sqrt(totalDistance));
                averageVariance.addValue(prices.getVariance());
                if (price <= 68 && price >= 67)
                    successes++;

                //            System.out.println(salesDepartment.getLatestObservation(SalesDataType.LAST_ASKED_PRICE));
                macroII.finish();

            }

            String[] csvLine = new String[5];
            csvLine[0] = currentP.toString();
            csvLine[1] = currentI.toString();
            csvLine[2] = String.valueOf(averageSquaredDistance.getMean());
            csvLine[3] = String.valueOf(averageVariance.getMean());
            csvLine[4] = String.valueOf(successes);
            writer.writeNext(csvLine);
            writer.flush();
            System.out.println(Arrays.toString(csvLine));

            currentI = currentI.add(increment).setScale(2);
            System.out.println();

        }

        currentP = currentP.add(increment).setScale(2);

    }

}

From source file:com.webbfontaine.valuewebb.model.validators.tt.FreightValueValidator.java

/**
 * Checks Freigh value against Freight Database considering containers, shipping line, port of load. port of dis.
 * This is done only when TT has containers with all equal size and type and if there is no LCL container.
 *//*  w ww . ja  va  2 s .c o  m*/
public void checkFreightValue() {

    ErrorHandling errorHandling = ErrorHandling.getInstance();

    TtTrans ttTrans = ttGen.getTtTrans();

    //check if error was already added
    List<TtLog> logs = ttGen.getLogs();
    for (TtLog log : logs) {
        if (!StringUtils.isEmpty(log.getMsg()) && log.getMsg().startsWith(Messages.FREIGHT_IN_RANGE)) {
            return;
        }
    }

    if (!ttTrans.checkIfAllContainersHaveSameTypeAndSize()) {
        return;
    }

    Freight freightSearchCriteria = constructFreightSearchCriteria(ttTrans);
    Freight freight = findFreight(freightSearchCriteria);

    if (freight != null) {
        BigDecimal fFreightInUsdForOneContainer = new Calculations().computeFreightForOneContainer(ttGen);

        if (freight.getMaxRate() != null && !(fFreightInUsdForOneContainer.compareTo(freight.getMaxRate()) <= 0
                && fFreightInUsdForOneContainer.compareTo(freight.getMinRate()) >= 0)) {
            ArrayList<FacesMessageText> msgs = new ArrayList<FacesMessageText>(1);
            msgs.add(new FacesMessageText(null,
                    Messages.FREIGHT_IN_RANGE + ": " + freight.getMinRate() + '-' + freight.getMaxRate(),
                    false));
            errorHandling.addErrorWithLinks("freightF", msgs, errorHandling.getErrorList(), false, true);
        }
    }
}

From source file:org.openmhealth.shim.ihealth.mapper.IHealthOxygenSaturationDataPointMapper.java

@Override
protected Optional<DataPoint<OxygenSaturation>> asDataPoint(JsonNode listEntryNode,
        Integer measureUnitMagicNumber) {

    BigDecimal bloodOxygenValue = asRequiredBigDecimal(listEntryNode, "BO");

    // iHealth has stated that missing values would most likely be represented as a 0 value for the field
    if (bloodOxygenValue.compareTo(ZERO) == 0) {
        return Optional.empty();
    }//from  w w  w .ja va  2s .com

    OxygenSaturation.Builder oxygenSaturationBuilder = new OxygenSaturation.Builder(
            new TypedUnitValue<>(PERCENT, bloodOxygenValue)).setMeasurementMethod(PULSE_OXIMETRY)
                    .setMeasurementSystem(PERIPHERAL_CAPILLARY);

    getEffectiveTimeFrameAsDateTime(listEntryNode).ifPresent(oxygenSaturationBuilder::setEffectiveTimeFrame);
    getUserNoteIfExists(listEntryNode).ifPresent(oxygenSaturationBuilder::setUserNotes);

    OxygenSaturation oxygenSaturation = oxygenSaturationBuilder.build();

    return Optional
            .of(new DataPoint<>(createDataPointHeader(listEntryNode, oxygenSaturation), oxygenSaturation));
}

From source file:org.eclipse.smarthome.ui.basic.internal.render.SetpointRenderer.java

/**
 * {@inheritDoc}/* w  ww .  j  a  v  a2s.c o  m*/
 */
@Override
public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException {
    Setpoint sp = (Setpoint) w;

    State state = itemUIRegistry.getState(w);
    String newLowerState = state.toString();
    String newHigherState = state.toString();

    // set defaults for min, max and step
    BigDecimal step = sp.getStep();
    if (step == null) {
        step = BigDecimal.ONE;
    }
    BigDecimal minValue = sp.getMinValue();
    if (minValue == null) {
        minValue = BigDecimal.ZERO;
    }
    BigDecimal maxValue = sp.getMaxValue();
    if (maxValue == null) {
        maxValue = BigDecimal.valueOf(100);
    }

    // if the current state is a valid value, we calculate the up and down step values
    if (state instanceof DecimalType) {
        DecimalType actState = (DecimalType) state;
        BigDecimal newLower = actState.toBigDecimal().subtract(step);
        BigDecimal newHigher = actState.toBigDecimal().add(step);
        if (newLower.compareTo(minValue) < 0) {
            newLower = minValue;
        }
        if (newHigher.compareTo(maxValue) > 0) {
            newHigher = maxValue;
        }
        newLowerState = newLower.toString();
        newHigherState = newHigher.toString();
    }

    String snippetName = "setpoint";
    String snippet = getSnippet(snippetName);

    snippet = preprocessSnippet(snippet, w);
    snippet = StringUtils.replace(snippet, "%newlowerstate%", newLowerState);
    snippet = StringUtils.replace(snippet, "%newhigherstate%", newHigherState);
    snippet = StringUtils.replace(snippet, "%value%", getValue(w));
    snippet = StringUtils.replace(snippet, "%minValue%", minValue.toString());
    snippet = StringUtils.replace(snippet, "%maxValue%", maxValue.toString());
    snippet = StringUtils.replace(snippet, "%step%", step.toString());

    // Process the color tags
    snippet = processColor(w, snippet);

    sb.append(snippet);
    return null;
}

From source file:de.hybris.platform.mpintgordermanagement.actions.returns.CaptureRefundAction.java

@Override
public Transition executeAction(final ReturnProcessModel process) throws RetryLaterException, Exception {
    LOG.debug("Process: " + process.getCode() + " in step " + getClass().getSimpleName());

    final ReturnRequestModel returnRequest = process.getReturnRequest();
    final List<PaymentTransactionModel> transactions = returnRequest.getOrder().getPaymentTransactions();

    if (transactions.isEmpty()) {
        LOG.info("Unable to refund for ReturnRequest " + returnRequest.getCode()
                + ", no PaymentTransactions found");
        setReturnRequestStatus(returnRequest, ReturnStatus.PAYMENT_FAILED);
        return Transition.NOK;
    }/*from   ww w.  j  av a 2 s  .  c o  m*/
    //This assumes that the Order only has one PaymentTransaction
    final PaymentTransactionModel transaction = transactions.get(0);

    final BigDecimal customRefundAmount = returnRequest.getCustomRefundAmount();
    BigDecimal amountToRefund = null;

    if (customRefundAmount != null && customRefundAmount.compareTo(new BigDecimal(0)) > 0) {
        amountToRefund = customRefundAmount;
    } else {
        amountToRefund = returnRequest.getOriginalRefundAmount();
    }

    Transition result;
    try {
        getPaymentService().refundFollowOn(transaction, amountToRefund);
        setReturnRequestStatus(returnRequest, ReturnStatus.PAYMENT_CAPTURED);
        result = Transition.OK;
    } catch (final AdapterException e) {
        LOG.info("Unable to refund for ReturnRequest " + returnRequest.getCode() + ", exception ocurred: "
                + e.getMessage());
        setReturnRequestStatus(returnRequest, ReturnStatus.PAYMENT_FAILED);
        result = Transition.NOK;
    }

    return result;
}