Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

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

Prototype

public BigDecimal multiply(BigDecimal multiplicand) 

Source Link

Document

Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()) .

Usage

From source file:nl.strohalm.cyclos.utils.DateHelper.java

/**
 * inverse function of decimalDaysBetween: adds a BigDecimal number of days to a Calendar.
 * @param date1 the date to which something is added
 * @param augend the number of days which is added, as a BigDecimal. May be negative.
 * @return null if one of the arguments is null, else the date + augend days.
 *///  ww w  .  ja v a  2s .  c o  m
public static Calendar decimalDaysAdd(final Calendar date1, final BigDecimal augend) {
    if (date1 == null || augend == null) {
        return null;
    }
    final BigDecimal date1InMillis = new BigDecimal(date1.getTimeInMillis());
    final BigDecimal augendInMillis = augend.multiply(new BigDecimal(DateUtils.MILLIS_PER_DAY));
    final BigDecimal resultAsBig = date1InMillis.add(augendInMillis);
    final Calendar result = Calendar.getInstance();
    result.setTimeInMillis(resultAsBig.longValue());
    return result;
}

From source file:org.cirdles.ambapo.UTMToLatLong.java

/**
 * // www  .j a  va 2 s.c o  m
 * @param originalTau
 * @param sigma
 * @param eccentricity
 * @param hemisphere
 * @return latitude
 */
private static BigDecimal calcLatitude(BigDecimal originalTau, BigDecimal sigma, BigDecimal eccentricity,
        char hemisphere) {

    BigDecimal funcOfTau = functionOfTau(originalTau, sigma, originalTau).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal changeInTau = changeInTau(eccentricity, originalTau, sigma);

    BigDecimal newTau = originalTau.subtract(funcOfTau.divide(changeInTau, PRECISION, RoundingMode.HALF_UP));

    BigDecimal latitude = (new BigDecimal(Math.atan(newTau.doubleValue())))
            .multiply(new BigDecimal(180.0 / Math.PI));

    if (hemisphere == 'S')
        latitude = latitude.multiply(new BigDecimal(-1));

    return latitude;

}

From source file:Main.java

/**
 * Compute e^x to a given scale. Break x into its whole and fraction parts
 * and compute (e^(1 + fraction/whole))^whole using Taylor's formula.
 * //from  w w  w. j  a  va2s  .co  m
 * @param x
 *            the value of x
 * @param scale
 *            the desired scale of the result
 * @return the result value
 */
public static BigDecimal exp(BigDecimal x, int scale) {
    // e^0 = 1
    if (x.signum() == 0) {
        return BigDecimal.valueOf(1);
    }

    // If x is negative, return 1/(e^-x).
    else if (x.signum() == -1) {
        return BigDecimal.valueOf(1).divide(exp(x.negate(), scale), scale, BigDecimal.ROUND_HALF_EVEN);
    }

    // Compute the whole part of x.
    BigDecimal xWhole = x.setScale(0, BigDecimal.ROUND_DOWN);

    // If there isn't a whole part, compute and return e^x.
    if (xWhole.signum() == 0) {
        return expTaylor(x, scale);
    }

    // Compute the fraction part of x.
    BigDecimal xFraction = x.subtract(xWhole);

    // z = 1 + fraction/whole
    BigDecimal z = BigDecimal.valueOf(1).add(xFraction.divide(xWhole, scale, BigDecimal.ROUND_HALF_EVEN));

    // t = e^z
    BigDecimal t = expTaylor(z, scale);

    BigDecimal maxLong = BigDecimal.valueOf(Long.MAX_VALUE);
    BigDecimal result = BigDecimal.valueOf(1);

    // Compute and return t^whole using intPower().
    // If whole > Long.MAX_VALUE, then first compute products
    // of e^Long.MAX_VALUE.
    while (xWhole.compareTo(maxLong) >= 0) {
        result = result.multiply(intPower(t, Long.MAX_VALUE, scale)).setScale(scale,
                BigDecimal.ROUND_HALF_EVEN);
        xWhole = xWhole.subtract(maxLong);

        Thread.yield();
    }
    return result.multiply(intPower(t, xWhole.longValue(), scale)).setScale(scale, BigDecimal.ROUND_HALF_EVEN);
}

From source file:com.spaceprogram.simplejpa.util.AmazonSimpleDBUtil.java

public static String encodeRealNumberRange(BigDecimal number, int maxDigitsLeft, int maxDigitsRight,
        BigDecimal offsetValue) {
    BigDecimal shiftMultiplier = new BigDecimal(Math.pow(10, maxDigitsRight));
    //        System.out.println("shiftMultiplier=" + shiftMultiplier);
    BigDecimal shiftedNumber = number.multiply(shiftMultiplier);
    //        System.out.println("shiftedNumber=" + shiftedNumber);
    shiftedNumber = shiftedNumber.setScale(0, BigDecimal.ROUND_HALF_UP);
    //        System.out.println("shiftedNumber rounded=" + shiftedNumber);
    BigDecimal shiftedOffset = offsetValue.multiply(shiftMultiplier);
    //        System.out.println("shiftedOffset=" + shiftedOffset);
    BigDecimal offsetNumber = shiftedNumber.add(shiftedOffset);
    //        System.out.println("offsetNumber=" + offsetNumber);
    String longString = offsetNumber.toString();
    //        System.out.println("shifted string=" + longString);
    int numBeforeDecimal = longString.length();
    int numZeroes = maxDigitsLeft + maxDigitsRight - numBeforeDecimal;
    StringBuffer strBuffer = new StringBuffer(numZeroes + longString.length());
    for (int i = 0; i < numZeroes; i++) {
        strBuffer.insert(i, '0');
    }//  w  w w  .j  ava2s.co  m
    strBuffer.append(longString);
    return strBuffer.toString();
}

From source file:com.aoindustries.website.signup.SignupCustomizeManagementActionHelper.java

/**
 * Gets the total monthly rate for the server, basic server + hardware options + management options
 *//*w w  w.j  a v a 2  s . c om*/
public static BigDecimal getTotalMonthlyRate(AOServConnector rootConn,
        SignupCustomizeServerForm signupCustomizeServerForm,
        SignupCustomizeManagementForm signupCustomizeManagementForm, PackageDefinition packageDefinition)
        throws SQLException, IOException {
    BigDecimal monthlyRate = SignupCustomizeServerActionHelper.getHardwareMonthlyRate(rootConn,
            signupCustomizeServerForm, packageDefinition);

    int totalDiskSpace = SignupCustomizeServerActionHelper.getTotalHardwareDiskSpace(rootConn,
            signupCustomizeServerForm);

    // Add the backup onsite option
    int backupOnsiteOption = signupCustomizeManagementForm.getBackupOnsiteOption();
    if (backupOnsiteOption != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits().get(backupOnsiteOption);
        BigDecimal rate = pdl.getAdditionalRate();
        if (rate != null)
            monthlyRate = monthlyRate.add(rate.multiply(BigDecimal.valueOf(totalDiskSpace)));
    }

    // Add the backup offsite option
    int backupOffsiteOption = signupCustomizeManagementForm.getBackupOffsiteOption();
    if (backupOffsiteOption != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits().get(backupOffsiteOption);
        BigDecimal rate = pdl.getAdditionalRate();
        if (rate != null)
            monthlyRate = monthlyRate.add(rate.multiply(BigDecimal.valueOf(totalDiskSpace)));
    }

    // Add the distributionScanOption option
    int distributionScanOption = signupCustomizeManagementForm.getDistributionScanOption();
    if (distributionScanOption != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits().get(distributionScanOption);
        BigDecimal rate = pdl.getAdditionalRate();
        if (rate != null)
            monthlyRate = monthlyRate.add(rate);
    }

    // Add the backup offsite option
    int failoverOption = signupCustomizeManagementForm.getFailoverOption();
    if (failoverOption != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits().get(failoverOption);
        String resourceName = pdl.getResource().getName();
        if (Resource.FAILOVER.equals(resourceName)) {
            // Failover mirror only
            BigDecimal rate = pdl.getAdditionalRate();
            if (rate != null)
                monthlyRate = monthlyRate.add(rate.multiply(BigDecimal.valueOf(totalDiskSpace)));
        } else if (Resource.MYSQL_REPLICATION.equals(resourceName)) {
            // Failover mirror plus MySQL replication
            Resource failoverResource = rootConn.getResources().get(Resource.FAILOVER);
            if (failoverResource == null)
                throw new SQLException("Unable to find Resource: " + Resource.FAILOVER);
            PackageDefinitionLimit failoverPDL = packageDefinition.getLimit(failoverResource);
            if (failoverPDL == null)
                throw new SQLException("Unable to find PackageDefinitionLimit: " + Resource.FAILOVER
                        + " on PackageDefinition #" + packageDefinition.getPkey());
            BigDecimal additionalRate = BigDecimal.valueOf(0, 2);
            BigDecimal failoverRate = failoverPDL.getAdditionalRate();
            if (failoverRate != null)
                additionalRate = failoverRate.multiply(BigDecimal.valueOf(totalDiskSpace));
            BigDecimal rate = pdl.getAdditionalRate();
            if (rate != null)
                additionalRate = additionalRate.add(rate);
            if (additionalRate != null)
                monthlyRate = monthlyRate.add(additionalRate);
        }
    }

    return monthlyRate;
}

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

private static List<DerivedDayAssignment> createAssignments(DerivedAllocation parent, BigDecimal alpha,
        List<Resource> resourcesFound, List<? extends DayAssignment> dayAssignments) {
    List<DerivedDayAssignment> result = new ArrayList<DerivedDayAssignment>();
    EffortDistributor distributor = new EffortDistributor(resourcesFound,
            AssignedEffortForResource.effortDiscounting(Collections.singletonList(parent)));
    for (DayAssignment each : dayAssignments) {
        int durationInSeconds = alpha.multiply(new BigDecimal(each.getDuration().getSeconds())).intValue();
        LocalDate day = each.getDay();
        List<ResourceWithAssignedDuration> distributeForDay = distributor
                .distributeForDay(PartialDay.wholeDay(day), seconds(durationInSeconds));
        result.addAll(asDerived(parent, day, distributeForDay));
    }//from   w ww  .j  ava 2s  .  c  o m
    return result;
}

From source file:org.cirdles.ambapo.UTMToLatLong.java

/**
 * //from w  w  w  .  j  av  a2 s.  c  om
 * @param eccentricity
 * @param currentTau
 * @param currentSigma
 * @return change in tau
 */
private static BigDecimal changeInTau(BigDecimal eccentricity, BigDecimal currentTau, BigDecimal currentSigma) {

    BigDecimal changeInTau = ((new BigDecimal(
            Math.sqrt((1 + currentSigma.pow(2).doubleValue()) * (1 + currentTau.pow(2).doubleValue()))))
                    .subtract(currentSigma.multiply(currentTau)))
                            .multiply(new BigDecimal(1 - eccentricity.pow(2).doubleValue()))
                            .multiply(new BigDecimal(Math.sqrt(1 + currentTau.pow(2).doubleValue())))
                            .divide(BigDecimal.ONE.add(BigDecimal.ONE.subtract(eccentricity.pow(2)))
                                    .multiply(currentTau.pow(2)), PRECISION, RoundingMode.HALF_UP);

    return changeInTau;

}

From source file:com.whatlookingfor.common.utils.StringUtils.java

/**
 * ???// w  w w.  j ava2  s.c  o m
 *
 * @param v1 
 * @param v2 
 * @return ?
 */
public static double mul(double v1, double v2) {
    BigDecimal b1 = new BigDecimal(Double.toString(v1));
    BigDecimal b2 = new BigDecimal(Double.toString(v2));
    return b1.multiply(b2).doubleValue();
}

From source file:com.breadwallet.tools.security.RequestHandler.java

public static RequestObject getRequestFromString(String str) {
    if (str == null || str.isEmpty())
        return null;
    RequestObject obj = new RequestObject();

    String tmp = str.trim().replaceAll("\n", "").replaceAll(" ", "%20");
    URI uri;//from   ww  w.j av a2s  .c om
    try {
        uri = URI.create(tmp);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    if (uri.getScheme() == null || !uri.getScheme().equals("bitcoin")) {
        tmp = "bitcoin://".concat(tmp);
    } else {
        tmp = tmp.replace("bitcoin:", "bitcoin://");
    }
    uri = URI.create(tmp);
    //        String[] parts = tmp.split("\\?", 2);
    String host = uri.getHost();
    if (host != null) {
        String addrs = host.trim();
        if (BRWalletManager.validateAddress(addrs)) {
            obj.address = addrs;
        }
    }
    String query = uri.getQuery();
    if (query == null)
        return obj;
    String[] params = query.split("&");
    for (String s : params) {
        String[] keyValue = s.split("=", 2);
        if (keyValue.length != 2)
            continue;
        if (keyValue[0].trim().equals("amount")) {
            try {
                BigDecimal bigDecimal = new BigDecimal(keyValue[1]);
                obj.amount = bigDecimal.multiply(new BigDecimal("100000000")).toString();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            //                Log.e(TAG, "amount: " + obj.amount);
        } else if (keyValue[0].trim().equals("label")) {
            obj.label = keyValue[1];
            //                Log.e(TAG, "label: " + obj.label);
        } else if (keyValue[0].trim().equals("message")) {
            obj.message = keyValue[1];
            //                Log.e(TAG, "message: " + obj.message);
        } else if (keyValue[0].trim().startsWith("req")) {
            obj.req = keyValue[1];
            //                Log.e(TAG, "req: " + obj.req);
        } else if (keyValue[0].trim().startsWith("r")) {
            obj.r = keyValue[1];
            //                Log.e(TAG, "r: " + obj.r);
        }
    }
    //        Log.e(TAG, "obj.address: " + obj.address);
    return obj;
}

From source file:biz.c24.io.spring.integration.samples.fpml.FpmlGenerator.java

private static TradeConfirmed randomizeFpML(TradeConfirmed tradeConfirmed) throws CloneNotSupportedException {
    ISO8601DateTime creationDate = new ISO8601DateTime(new Date());
    ISO8601Date tradeDate = new ISO8601Date(new GregorianCalendar(2011, Calendar.JULY, 5).getTime());
    ISO8601Date expiryDate = new ISO8601Date(new GregorianCalendar(2012, Calendar.JANUARY, 5).getTime());
    ISO8601Date settlementDate = new ISO8601Date(new GregorianCalendar(2011, Calendar.JULY, 7).getTime());
    ISO8601Date valueDate = new ISO8601Date(new GregorianCalendar(2012, Calendar.JANUARY, 9).getTime());

    Random random = new Random();

    BigDecimal putAmount = new BigDecimal((1 + random.nextInt(999)) * 100000.);
    BigDecimal callAmount = new BigDecimal((1 + random.nextInt(999)) * 100000.);
    BigDecimal fxRate = callAmount.divide(putAmount, 8, RoundingMode.HALF_EVEN).setScale(5,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal premiumValue = new BigDecimal(0.001).setScale(5, BigDecimal.ROUND_HALF_UP);
    BigDecimal premiumAmount = callAmount.multiply(premiumValue).setScale(2, BigDecimal.ROUND_HALF_UP);

    String sendTo = "SendTo" + random.nextInt(999999);
    String sentBy = "SentBy" + random.nextInt(999999);
    String msgId = "Msg" + random.nextInt(999999);
    String conversationId = "Conv" + random.nextInt(999999);
    String tradeId1 = "ID1:" + random.nextInt(999999);
    String tradeId2 = "ID2:" + random.nextInt(999999);

    // Set the header
    NotificationMessageHeader header = tradeConfirmed.getHeader();
    header.getMessageHeadermodel().setCreationTimestamp(creationDate);
    header.getConversationId().setValue(conversationId);
    header.getMessageId().setValue(msgId);
    header.getMessageHeadermodel().getSentBy().setValue(sentBy);
    header.getMessageHeadermodel().getSendTo()[0].setValue(sendTo);

    // Set the TradeHeader
    TradeHeader tradeHeader = tradeConfirmed.getTrade().getTradeHeader();
    tradeHeader.getPartyTradeIdentifier()[0].getTradeIdentifierSG1()[0].getTradeId().setValue(tradeId1);
    tradeHeader.getPartyTradeIdentifier()[1].getTradeIdentifierSG1()[0].getTradeId().setValue(tradeId2);
    tradeHeader.getTradeDate().setValue(tradeDate);

    FxOptionLeg fxOptionLeg = (FxOptionLeg) tradeConfirmed.getTrade().getProduct();
    fxOptionLeg.getExpiryDateTime().setExpiryDate(expiryDate);

    FxOptionPremium optionPremium = fxOptionLeg.getFxOptionPremium()[0];
    optionPremium.getPremiumAmount().setAmount(premiumAmount);
    optionPremium.setPremiumSettlementDate(settlementDate);
    SettlementInstruction settlementInstruction = optionPremium.getSettlementInformation()
            .getSettlementInstruction();
    settlementInstruction.getCorrespondentInformation().getRoutingIdentificationmodel().getRoutingIds()
            .getRoutingId()[0].setValue(sendTo);
    settlementInstruction.getBeneficiary().getRoutingIdentificationmodel().getRoutingIds().getRoutingId()[0]
            .setValue(sentBy);//from w w w  . j a v  a2  s. co m
    optionPremium.getPremiumQuote().setPremiumValue(premiumValue);
    fxOptionLeg.setValueDate(valueDate);

    fxOptionLeg.getPutCurrencyAmount().getCurrency().setValue("AUD");
    fxOptionLeg.getPutCurrencyAmount().setAmount(putAmount);

    fxOptionLeg.getPutCurrencyAmount().getCurrency().setValue("USD");
    fxOptionLeg.getCallCurrencyAmount().setAmount(callAmount);

    fxOptionLeg.getFxStrikePrice().setRate(fxRate);

    fxOptionLeg.getQuotedAs().getOptionOnCurrency().setValue("AUD");
    fxOptionLeg.getQuotedAs().getFaceOnCurrency().setValue("USD");
    fxOptionLeg.getQuotedAs().getQuotedTenor().setPeriod("M");
    fxOptionLeg.getQuotedAs().getQuotedTenor().setPeriodMultiplier(new BigInteger("6"));

    tradeConfirmed.getParty()[0].getPartyId()[0].setValue(sendTo);
    tradeConfirmed.getParty()[1].getPartyId()[0].setValue(sentBy);

    return (TradeConfirmed) tradeConfirmed.cloneDeep();
}