Example usage for java.math BigDecimal ONE

List of usage examples for java.math BigDecimal ONE

Introduction

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

Prototype

BigDecimal ONE

To view the source code for java.math BigDecimal ONE.

Click Source Link

Document

The value 1, with a scale of 0.

Usage

From source file:org.openhab.persistence.dynamodb.internal.AbstractDynamoDBItemSerializationTest.java

@Test
public void testOnOffTypeWithSwitchItem() throws IOException {
    DynamoDBItem<?> dbitemOff = testStateGeneric(OnOffType.OFF, BigDecimal.ZERO);
    testAsHistoricGeneric(dbitemOff, new SwitchItem("foo"), OnOffType.OFF);

    DynamoDBItem<?> dbitemOn = testStateGeneric(OnOffType.ON, BigDecimal.ONE);
    testAsHistoricGeneric(dbitemOn, new SwitchItem("foo"), OnOffType.ON);
}

From source file:org.libreplan.business.planner.entities.StretchesFunction.java

@AssertTrue(message = "Last stretch should have one hundred percent "
        + "length and one hundred percent of work percentage")
public boolean isOneHundredPercentConstraint() {
    List<Stretch> stretches = getStretchesPlusConsolidated();
    if (stretches.isEmpty()) {
        return false;
    }//w w w  . ja  va 2s.co m

    Stretch lastStretch = stretches.get(stretches.size() - 1);
    if (lastStretch.getLengthPercentage().compareTo(BigDecimal.ONE) != 0) {
        return false;
    }

    if (lastStretch.getAmountWorkPercentage().compareTo(BigDecimal.ONE) != 0) {
        return false;
    }

    return true;
}

From source file:com.opengamma.examples.bloomberg.loader.DemoEquityOptionCollarPortfolioLoader.java

private void addNodes(final ManageablePortfolioNode rootNode, final String underlying,
        final boolean includeUnderlying, final Period[] expiries) {
    final ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying);
    ManageableSecurity underlyingSecurity = null;
    if (includeUnderlying) {
        underlyingSecurity = getOrLoadEquity(ticker);
    }/*from  w  w  w . j a v  a 2  s.co  m*/

    final ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker)
            : underlyingSecurity.getExternalIdBundle();
    final HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle);
    final double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo);
    final Set<ExternalId> optionChain = getOptionChain(ticker);

    //TODO: reuse positions/nodes?
    final String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName();
    final String formattedName = MessageFormatter.format("[{}] {}", underlying, longName).getMessage();
    final ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName);

    final BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike),
            BigDecimal.ROUND_HALF_EVEN);

    if (includeUnderlying) {
        addPosition(equityNode, underlyingAmount, ticker);
    }

    final TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>();
    for (final ExternalId optionTicker : optionChain) {
        s_logger.debug("Got option {}", optionTicker);

        final BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption
                .getOptionParser(optionTicker);
        s_logger.debug("Got option info {}", optionInfo);

        final LocalDate key = optionInfo.getExpiry();
        Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key);
        if (set == null) {
            set = new HashSet<BloombergTickerParserEQOption>();
            optionsByExpiry.put(key, set);
        }
        set.add(optionInfo);
    }
    final Set<ExternalId> tickersToLoad = new HashSet<ExternalId>();

    final BigDecimal expiryCount = BigDecimal.valueOf(expiries.length);
    final BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN);
    final BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE);
    int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue();

    for (final Period bucketPeriod : expiries) {
        final ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(
                bucketPeriod.toString().substring(1));

        final LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run
        final LocalDate targetExpiry = nowish.plus(bucketPeriod);
        final LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry);
        if (chosenExpiry == null) {
            s_logger.info("No options for {} on {}", targetExpiry, underlying);
            continue;
        }
        s_logger.info("Using time {} for bucket {} ({})",
                new Object[] { chosenExpiry, bucketPeriod, targetExpiry });

        final Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry);
        final TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<>();
        for (final BloombergTickerParserEQOption option : optionsAtExpiry) {
            //        s_logger.info("option {}", option);
            final double key = option.getStrike();
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key);
            if (pair == null) {
                pair = Pair.of(null, null);
            }
            if (option.getOptionType() == OptionType.CALL) {
                pair = Pair.of(option, pair.getSecond());
            } else {
                pair = Pair.of(pair.getFirst(), option);
            }
            optionsByStrike.put(key, pair);
        }

        //cascading collar?
        final BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry;

        s_logger.info(" est strike {}", estimatedCurrentStrike);
        final Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]);

        int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike);
        if (strikeIndex < 0) {
            strikeIndex = -(1 + strikeIndex);
        }
        s_logger.info("strikes length {} index {} strike of index {}",
                new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex),
                        Double.valueOf(strikes[strikeIndex]) });

        int minIndex = strikeIndex - _numOptions;
        minIndex = Math.max(0, minIndex);
        int maxIndex = strikeIndex + _numOptions;
        maxIndex = Math.min(strikes.length - 1, maxIndex);

        s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex));
        final StringBuffer sb = new StringBuffer("strikes: [");
        for (int j = minIndex; j <= maxIndex; j++) {
            sb.append(" ");
            sb.append(strikes[j]);
        }
        sb.append(" ]");
        s_logger.info(sb.toString());

        //Short Calls
        final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = minIndex; j < strikeIndex; j++) {
            final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            calls.add(pair);
        }
        spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying,
                calls.size());

        // Long Puts
        final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = strikeIndex + 1; j <= maxIndex; j++) {
            final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            puts.add(pair);
        }
        spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying,
                puts.size());

        if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) {
            equityNode.addChildNode(bucketNode); //Avoid generating empty nodes
        }
    }

    for (final ExternalId optionTicker : tickersToLoad) {
        final ManageableSecurity loaded = getOrLoadSecurity(optionTicker);
        if (loaded == null) {
            throw new OpenGammaRuntimeException("Unexpected option type " + loaded);
        }

        //TODO [LAPANA-29] Should be able to do this for index options too
        if (includeUnderlying) {
            try {
                final HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker,
                        loaded.getExternalIdBundle());
                if (loadedTs == null) {
                    throw new OpenGammaRuntimeException("Failed to get time series for " + loaded);
                }
            } catch (final Exception ex) {
                s_logger.info("Failed to get time series for " + loaded, ex);
            }
        }
    }

    if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) {
        rootNode.addChildNode(equityNode);
    }
}

From source file:org.egov.infra.gis.service.GeoLocationService.java

private static String getStyleColorName(BigDecimal wardWiseNos, BigDecimal wardDataMinAmount,
        Integer totalNoOfColors, BigDecimal rangeSize) {

    return "#color" + (BigDecimal.valueOf(totalNoOfColors)
            .subtract((wardWiseNos.subtract(wardDataMinAmount).subtract(BigDecimal.ONE)).divide(rangeSize, 0,
                    BigDecimal.ROUND_DOWN)));

}

From source file:uk.dsxt.voting.client.web.MockVotingApiResource.java

License:asdf

@POST
@Path("/getAllClientVotes")
@Produces("application/json")
public RequestResult getAllClientVotes(@FormParam("cookie") String cookie,
        @FormParam("votingId") String votingId) {
    final VoteResultWeb[] results = new VoteResultWeb[10];

    results[0] = new VoteResultWeb(votingId, "Voting Name 2016", "client_1", "Dr. Watson", BigDecimal.TEN,
            VoteResultStatus.OK, "message_1");
    results[1] = new VoteResultWeb(votingId, "Voting Name 2016", "client_2", "Mr. Drow", BigDecimal.ONE,
            VoteResultStatus.OK, "message_2");
    results[2] = new VoteResultWeb(votingId, "Voting Name 2016", "client_3", "Mrs. Smith", BigDecimal.ZERO,
            VoteResultStatus.SignatureFailed, "message_3");
    results[3] = new VoteResultWeb(votingId, "Voting Name 2016", "client_4", "Mr. Zuba", BigDecimal.ZERO,
            VoteResultStatus.OK, "message_4");
    results[4] = new VoteResultWeb(votingId, "Voting Name 2016", "client_5", "Mr. Lenin",
            new BigDecimal(24324234), VoteResultStatus.SignatureFailed, "message_5");
    results[5] = new VoteResultWeb(votingId, "Voting Name 2016", "client_6", "Mr. Kak", BigDecimal.ONE,
            VoteResultStatus.OK, "message_6");
    results[6] = new VoteResultWeb(votingId, "Voting Name 2016", "client_7", "Mrs. Drow", BigDecimal.ZERO,
            VoteResultStatus.SignatureFailed, "message_7");
    results[7] = new VoteResultWeb(votingId, "Voting Name 2016", "client_8", "Mr. Smith", BigDecimal.ZERO,
            VoteResultStatus.OK, "message_8");
    results[8] = new VoteResultWeb(votingId, "Voting Name 2016", "client_9", "Mr. Stalin",
            new BigDecimal(6435674), VoteResultStatus.SignatureFailed, "message_9");
    results[9] = new VoteResultWeb(votingId, "Voting Name 2016", "client_10", "Mr. Kalinin",
            new BigDecimal(5632626), VoteResultStatus.OK, "message_10");

    return new RequestResult<>(results, null);
}

From source file:com.heliumv.api.inventory.InventoryApi.java

private boolean isDifferenceToLarge(BigDecimal baseAmount, BigDecimal newAmount) {
    BigDecimal percentAllowed = new BigDecimal(10);
    BigDecimal amplitude = baseAmount.movePointLeft(2).multiply(percentAllowed);
    if (amplitude.compareTo(BigDecimal.ONE) <= 0) {
        amplitude = BigDecimal.ONE;
    }//from www.j ava 2 s.c o  m
    return baseAmount.subtract(newAmount).abs().compareTo(amplitude) > 0;
}

From source file:org.estatio.dom.lease.invoicing.InvoiceCalculationService.java

/**
 * Calculates an invoice item with the difference between the already
 * invoiced and calculated value./*from w  ww.ja  v a  2s.c  o  m*/
 * 
 * @param leaseTerm
 * @param dueDate
 * @param calculationResult
 * @param invoicingFrequency
 */
void createInvoiceItems(final LeaseTerm leaseTerm, final InvoiceCalculationParameters parameters,
        final List<CalculationResult> results) {

    for (CalculationResult result : results) {
        // TODO: this is a hack to speed up processing by ignoring zero
        // values on a normal run
        if (result.value().compareTo(BigDecimal.ZERO) != 0
                || parameters.invoiceRunType().equals(InvoiceRunType.RETRO_RUN)) {
            BigDecimal invoicedValue = invoiceItemsForLease.invoicedValue(leaseTerm,
                    result.invoicingInterval().asLocalDateInterval());
            BigDecimal newValue = result.value().subtract(invoicedValue).subtract(result.mockValue());
            if (newValue.compareTo(BigDecimal.ZERO) != 0) {
                boolean adjustment = invoicedValue.add(result.mockValue()).compareTo(BigDecimal.ZERO) != 0;
                InvoiceItemForLease invoiceItem = invoiceItemsForLease.createUnapprovedInvoiceItem(leaseTerm,
                        result.invoicingInterval().asLocalDateInterval(), parameters.invoiceDueDate(),
                        interactionId);
                invoiceItem.setNetAmount(newValue);
                invoiceItem.setQuantity(BigDecimal.ONE);
                LeaseItem leaseItem = leaseTerm.getLeaseItem();
                Charge charge = leaseItem.getCharge();
                invoiceItem.setCharge(charge);
                invoiceItem.setDescription(charge.getDescription());
                invoiceItem.setDueDate(parameters.invoiceDueDate());
                invoiceItem.setStartDate(result.invoicingInterval().startDate());
                invoiceItem.setEndDate(result.invoicingInterval().endDate());

                LocalDateInterval intervalToUse = adjustment ? result.invoicingInterval().asLocalDateInterval()
                        : result.effectiveInterval();
                invoiceItem.setEffectiveStartDate(intervalToUse.startDate());
                invoiceItem.setEffectiveEndDate(intervalToUse.endDate());

                invoiceItem.setTax(leaseItem.getEffectiveTax());
                invoiceItem.verify();
                invoiceItem.setAdjustment(adjustment);
            }
        }
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Euler-Mascheroni constant./* w w w  .  j a v  a 2s .  c  om*/
 *
 * @param mc The required precision of the result.
 * @return 0.577...
 */
static public BigDecimal gamma(MathContext mc) {
    /* look it up if possible */
    if (mc.getPrecision() < GAMMA.precision()) {
        return GAMMA.round(mc);
    } else {
        double eps = prec2err(0.577, mc.getPrecision());
        /* Euler-Stieltjes as shown in Dilcher, Aequat Math 48 (1) (1994) 55-85
        14
         */
        MathContext mcloc = new MathContext(2 + mc.getPrecision());
        BigDecimal resul = BigDecimal.ONE;
        resul = resul.add(log(2, mcloc));
        resul = resul.subtract(log(3, mcloc));
        /* how many terms: zeta-1 falls as 1/2^(2n+1), so the
         * terms drop faster than 1/2^(4n+2). Set 1/2^(4kmax+2) < eps.
         * Leading term zeta(3)/(4^1*3) is 0.017. Leading zeta(3) is 1.2. Log(2) is 0.7
         */
        int kmax = (int) ((Math.log(eps / 0.7) - 2.) / 4.);
        mcloc = new MathContext(1 + err2prec(1.2, eps / kmax));
        for (int n = 1;; n++) {
            /* zeta is close to 1. Division of zeta-1 through
             * 4^n*(2n+1) means divion through roughly 2^(2n+1)
             */
            BigDecimal c = zeta(2 * n + 1, mcloc).subtract(BigDecimal.ONE);
            BigInteger fourn = new BigInteger("" + (2 * n + 1));
            fourn = fourn.shiftLeft(2 * n);
            c = divideRound(c, fourn);
            resul = resul.subtract(c);
            if (c.doubleValue() < 0.1 * eps) {
                break;
            }
        }
        return resul.round(mc);
    }
}

From source file:com.premiumminds.billy.core.services.builders.impl.GenericInvoiceEntryBuilderImpl.java

protected void validateValues() throws ValidationException {
    MathContext mc = BillyMathContext.get();

    GenericInvoiceEntryEntity e = this.getTypeInstance();

    for (Tax t : e.getProduct().getTaxes()) {
        if (this.daoContext.isSubContext(t.getContext(), this.context)) {
            Date taxDate = e.getTaxPointDate() == null ? new Date() : e.getTaxPointDate();
            if (DateUtils.isSameDay(t.getValidTo(), taxDate) || t.getValidTo().after(taxDate)) {
                e.getTaxes().add(t);// w  ww . ja v a 2  s.c  o m
            }
        }
    }
    if (e.getTaxes().isEmpty()) {
        throw new ValidationException(
                GenericInvoiceEntryBuilderImpl.LOCALIZER.getString("exception.invalid_taxes"));
    }

    e.setUnitDiscountAmount(BigDecimal.ZERO); // TODO

    if (e.getUnitAmountWithTax() != null) {
        BigDecimal unitAmountWithoutTax = e.getUnitAmountWithTax();
        BigDecimal unitTaxAmount = BigDecimal.ZERO;
        for (Tax t : this.getTypeInstance().getTaxes()) {
            switch (t.getTaxRateType()) {
            case FLAT:
                unitAmountWithoutTax = unitAmountWithoutTax.subtract(t.getValue(), mc);
                unitTaxAmount = unitTaxAmount.add(t.getValue(), mc);
                break;
            case PERCENTAGE:
                unitAmountWithoutTax = e.getUnitAmountWithTax().divide(
                        BigDecimal.ONE.add(t.getPercentageRateValue().divide(new BigDecimal("100"), mc), mc),
                        mc);
                unitTaxAmount = unitTaxAmount.add(e.getUnitAmountWithTax().subtract(unitAmountWithoutTax, mc),
                        mc);

                break;
            default:
                break;
            }
        }
        e.setUnitAmountWithoutTax(unitAmountWithoutTax);
        e.setUnitTaxAmount(unitTaxAmount);

        // Minus discounts
        e.setUnitAmountWithoutTax(unitAmountWithoutTax.subtract(e.getUnitDiscountAmount(), mc));
    } else {
        BigDecimal unitAmountWithTax = e.getUnitAmountWithoutTax();
        BigDecimal unitTaxAmount = BigDecimal.ZERO;

        for (Tax t : this.getTypeInstance().getTaxes()) {
            switch (t.getTaxRateType()) {
            case FLAT:
                unitAmountWithTax = unitAmountWithTax.add(t.getValue(), mc);
                unitTaxAmount = unitTaxAmount.add(t.getValue(), mc);
                break;
            case PERCENTAGE:
                unitTaxAmount = unitTaxAmount.add(e.getUnitAmountWithoutTax()
                        .multiply(t.getPercentageRateValue(), mc).divide(new BigDecimal("100"), mc), mc);
                unitAmountWithTax = unitAmountWithTax.add(unitTaxAmount, mc);
                break;
            default:
                break;
            }
        }

        e.setUnitAmountWithTax(unitAmountWithTax);
        e.setUnitTaxAmount(unitTaxAmount);

    }

    e.setAmountWithTax(this.getTypeInstance().getUnitAmountWithTax().multiply(e.getQuantity(), mc));
    e.setAmountWithoutTax(this.getTypeInstance().getUnitAmountWithoutTax().multiply(e.getQuantity(), mc));
    e.setTaxAmount(this.getTypeInstance().getUnitTaxAmount().multiply(e.getQuantity(), mc));
    e.setDiscountAmount(this.getTypeInstance().getUnitDiscountAmount().multiply(e.getQuantity(), mc));
}

From source file:org.ng200.openolympus.ContestTest.java

public void createDummySolution(long time, Task task, User user, int baseTestScore, int mainTestScore,
        boolean tested) {
    Solution solution = new Solution(task, user, "", new Date(time));
    if (baseTestScore == 0 && mainTestScore == 0) {
        solution.setTested(tested);//from  www. j a  v a2  s  . c o m
    }
    solution = this.solutionService.saveSolution(solution);
    for (int i = 0; i < baseTestScore; i++) {
        final Verdict verdict = new Verdict(solution, BigDecimal.ONE, "a", true);
        verdict.setTested(tested);
        verdict.setScore(BigDecimal.ONE);
        verdict.setStatus(Result.OK);
        this.solutionService.saveVerdict(verdict);
    }
    for (int i = 0; i < mainTestScore; i++) {
        final Verdict verdict = new Verdict(solution, BigDecimal.ONE, "a", false);
        verdict.setTested(tested);
        verdict.setScore(BigDecimal.ONE);
        verdict.setStatus(Result.OK);
        this.solutionService.saveVerdict(verdict);
    }

    Assert.assertEquals(this.solutionRepository.findOne(solution.getId()).isTested(), tested);
}