List of usage examples for java.math BigDecimal divide
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
From source file:hjow.hgtable.util.DataUtil.java
/** * <p>2? 1 ? .</p>/*from w w w. j av a2s .co m*/ * * @param original : ?? * @param scale : ? * @return 2? 1 */ public static BigDecimal sqrt(BigDecimal original, int scale) { BigDecimal temp = new BigDecimal(String.valueOf(original)); BigDecimal results = new BigDecimal("1.0"); results.setScale(scale + 2); int loops = 0; while (true) { if (loops >= 1) { temp = new BigDecimal(String.valueOf(results)); } temp.setScale(scale + 2, BigDecimal.ROUND_FLOOR); results = original.divide(temp, scale + 2, BigDecimal.ROUND_FLOOR).add(temp) .divide(new BigDecimal("2.0"), scale + 2, BigDecimal.ROUND_FLOOR); if (temp.equals(results)) break; loops++; } return results.setScale(scale, BigDecimal.ROUND_HALF_UP); }
From source file:CentralLimitTheorem.CLT.java
public void ModelDynamics(int size, double prob) { sampleSize = size;//from w w w .j av a2 s .com probability = prob; double m = sampleSize * probability; double variance_2 = sampleSize * probability * (1. - probability); for (int i = 0; i <= 1000; i++) { double x = (double) i * ((double) sampleSize / 1000.); double exponent = Math.pow(x - m, 2.0) / (2 * variance_2); double scale = Math.exp((-1.) * exponent); double coeff = Math.sqrt(variance_2 * 2. * Math.PI); BigDecimal coeffBD = new BigDecimal(coeff); BigDecimal scaleBD = new BigDecimal(scale); prob_x[i] = scaleBD.divide(coeffBD, 40, RoundingMode.HALF_UP); } for (int i = 0; i <= sampleSize; i++) { BigInteger ntF = factorial(sampleSize); BigInteger denom = factorial(i).multiply(factorial(sampleSize - i)); BigDecimal ntFBD = new BigDecimal(ntF); BigDecimal denomBD = new BigDecimal(denom); BigDecimal quotient = ntFBD.divide(denomBD, 40, RoundingMode.HALF_UP); BigDecimal restBD = BigDecimal.valueOf( Math.pow(probability, (double) i) * Math.pow(1. - probability, (double) sampleSize - i)); prob_k[i] = quotient.multiply(restBD); System.out.format("[%d]\t%.20f\n", i, prob_k[i]); } }
From source file:org.kuali.ole.fp.document.service.impl.DisbursementVoucherTaxServiceImpl.java
/** * Generates an accounting line for the chart, account, object code & tax percentage values given. * /*from www .j a va2s.c om*/ * @param document The disbursement voucher the tax will be applied to. * @param chart The chart code to be assigned to the accounting line generated. * @param account The account code to be assigned to the accounting line generated. * @param objectCode The object code used on the accounting line generated. * @param taxPercent The tax rate to be used to calculate the tax amount. * @param taxableAmount The total amount that is taxable. This amount is used in conjunction with the tax percent * to calculate the amount for the accounting lined being generated. * @return A fully populated AccountingLine instance representing the amount of tax that will be applied to the * disbursement voucher provided. */ protected AccountingLine generateTaxAccountingLine(DisbursementVoucherDocument document, String chart, String account, String objectCode, KualiDecimal taxPercent, KualiDecimal taxableAmount) { AccountingLine taxLine = null; try { taxLine = (SourceAccountingLine) document.getSourceAccountingLineClass().newInstance(); } catch (IllegalAccessException e) { throw new IllegalArgumentException("unable to access sourceAccountingLineClass", e); } catch (InstantiationException e) { throw new IllegalArgumentException("unable to instantiate sourceAccountingLineClass", e); } taxLine.setDocumentNumber(document.getDocumentNumber()); taxLine.setSequenceNumber(document.getNextSourceLineNumber()); taxLine.setChartOfAccountsCode(chart); taxLine.setAccountNumber(account); taxLine.setFinancialObjectCode(objectCode); // calculate tax amount and set as line amount BigDecimal amount = taxableAmount.bigDecimalValue(); BigDecimal tax = taxPercent.bigDecimalValue(); BigDecimal taxDecimal = tax.divide(new BigDecimal(100), 5, BigDecimal.ROUND_HALF_UP); KualiDecimal taxAmount = new KualiDecimal( amount.multiply(taxDecimal).setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)); taxLine.setAmount(taxAmount.negated()); return taxLine; }
From source file:org.kuali.kfs.fp.document.service.impl.DisbursementVoucherTaxServiceImpl.java
/** * Generates an accounting line for the chart, account, object code & tax percentage values given. * /* w ww . j av a2s . c o m*/ * @param document The disbursement voucher the tax will be applied to. * @param chart The chart code to be assigned to the accounting line generated. * @param account The account code to be assigned to the accounting line generated. * @param objectCode The object code used on the accounting line generated. * @param taxPercent The tax rate to be used to calculate the tax amount. * @param taxableAmount The total amount that is taxable. This amount is used in conjunction with the tax percent * to calculate the amount for the accounting lined being generated. * @return A fully populated AccountingLine instance representing the amount of tax that will be applied to the * disbursement voucher provided. */ protected AccountingLine generateTaxAccountingLine(DisbursementVoucherDocument document, String chart, String account, String objectCode, KualiDecimal taxPercent, KualiDecimal taxableAmount) { AccountingLine taxLine = null; try { taxLine = (SourceAccountingLine) document.getSourceAccountingLineClass().newInstance(); } catch (IllegalAccessException e) { throw new InfrastructureException("unable to access sourceAccountingLineClass", e); } catch (InstantiationException e) { throw new InfrastructureException("unable to instantiate sourceAccountingLineClass", e); } taxLine.setDocumentNumber(document.getDocumentNumber()); taxLine.setSequenceNumber(document.getNextSourceLineNumber()); taxLine.setChartOfAccountsCode(chart); taxLine.setAccountNumber(account); taxLine.setFinancialObjectCode(objectCode); // calculate tax amount and set as line amount BigDecimal amount = taxableAmount.bigDecimalValue(); BigDecimal tax = taxPercent.bigDecimalValue(); BigDecimal taxDecimal = tax.divide(new BigDecimal(100), 5, BigDecimal.ROUND_HALF_UP); KualiDecimal taxAmount = new KualiDecimal( amount.multiply(taxDecimal).setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)); taxLine.setAmount(taxAmount.negated()); return taxLine; }
From source file:org.yes.cart.payment.impl.PayPalProPaymentGatewayImpl.java
private NvpBuilder createAuthRequest(final Payment payment, final String paymentAction) { final NvpBuilder npvs = new NvpBuilder(); npvs.addRaw("PAYMENTACTION", paymentAction); npvs.addRaw("INVNUM", payment.getOrderShipment()); npvs.addRaw("CREDITCARDTYPE", payment.getCardType()); npvs.addRaw("ACCT", payment.getCardNumber()); npvs.addRaw("EXPDATE", payment.getCardExpireMonth() + payment.getCardExpireYear()); npvs.addRaw("CVV2", payment.getCardCvv2Code()); npvs.addRaw("AMT", payment.getPaymentAmount().setScale(2, RoundingMode.HALF_UP).toString()); npvs.addRaw("CURRENCYCODE", payment.getOrderCurrency()); int i = 0;// w w w . j a va 2 s . c om BigDecimal itemsNetTotal = Total.ZERO; BigDecimal ship = Total.ZERO; for (final PaymentLine item : payment.getOrderItems()) { if (item.isShipment()) { ship = item.getUnitPrice(); } else { final BigDecimal intQty = item.getQuantity().setScale(0, RoundingMode.CEILING); final String skuName; final BigDecimal qty; if (MoneyUtils.isFirstEqualToSecond(intQty, item.getQuantity())) { // integer qty skuName = item.getSkuName(); qty = intQty.stripTrailingZeros(); } else { // fractional qty skuName = item.getQuantity().toPlainString().concat("x ").concat(item.getSkuName()); qty = BigDecimal.ONE; } npvs.addEncoded("L_NUMBER" + i, item.getSkuCode().length() > ITEMSKU ? item.getSkuCode().substring(0, ITEMSKU - 1) + "~" : item.getSkuCode()); npvs.addEncoded("L_NAME" + i, skuName.length() > ITEMNAME ? skuName.substring(0, ITEMNAME - 1) + "~" : skuName); npvs.addRaw("L_QTY" + i, qty.stripTrailingZeros().toPlainString()); final BigDecimal itemNetAmount = item.getUnitPrice().multiply(item.getQuantity()) .subtract(item.getTaxAmount()).setScale(Total.ZERO.scale(), RoundingMode.HALF_UP); final BigDecimal itemNetPricePerAdjustedQty = itemNetAmount.divide(qty, Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP); // Need to do this to overcome rounding final BigDecimal restoredNetAmount = itemNetPricePerAdjustedQty.multiply(qty) .setScale(Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP); itemsNetTotal = itemsNetTotal.add(restoredNetAmount); // final BigDecimal taxUnit = MoneyUtils.isFirstBiggerThanSecond(item.getTaxAmount(), Total.ZERO) ? item.getTaxAmount().divide(qty, Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP) : Total.ZERO; npvs.addRaw("L_AMT" + i, itemNetPricePerAdjustedQty.toPlainString()); // npvs.addRaw("L_TAXAMT" + i, taxUnit.toPlainString()); i++; } } final BigDecimal itemsAndShipping = itemsNetTotal.add(ship); final BigDecimal paymentNet = payment.getPaymentAmount().subtract(payment.getTaxAmount()); if (MoneyUtils.isFirstBiggerThanSecond(itemsAndShipping, paymentNet)) { npvs.addRaw("SHIPDISCAMT", paymentNet.subtract(itemsAndShipping).toPlainString()); } npvs.addRaw("ITEMAMT", itemsNetTotal.toPlainString()); npvs.addRaw("SHIPPINGAMT", ship.toPlainString()); npvs.addRaw("TAXAMT", payment.getTaxAmount().toPlainString()); if (payment.getBillingAddress() != null) { npvs.addEncoded("EMAIL", payment.getBillingEmail()); npvs.addEncoded("FIRSTNAME", payment.getBillingAddress().getFirstname()); npvs.addEncoded("LASTNAME", payment.getBillingAddress().getLastname()); npvs.addEncoded("STREET", payment.getBillingAddress().getAddrline1()); if (StringUtils.isNotBlank(payment.getBillingAddress().getAddrline2())) { npvs.addEncoded("STREET2", payment.getBillingAddress().getAddrline2()); } npvs.addEncoded("CITY", payment.getBillingAddress().getCity()); npvs.addEncoded("STATE", payment.getBillingAddress().getStateCode()); npvs.addEncoded("ZIP", payment.getBillingAddress().getStateCode()); npvs.addEncoded("COUNTRYCODE", payment.getBillingAddress().getCountryCode()); } if (payment.getShippingAddress() != null) { npvs.addEncoded("SHIPTONAME", payment.getShippingAddress().getFirstname() + " " + payment.getShippingAddress().getLastname()); npvs.addEncoded("SHIPTOSTREET", payment.getShippingAddress().getAddrline1()); if (StringUtils.isNotBlank(payment.getShippingAddress().getAddrline2())) { npvs.addEncoded("SHIPTOSTREET2", payment.getShippingAddress().getAddrline2()); } npvs.addEncoded("SHIPTOCITY", payment.getShippingAddress().getCity()); npvs.addEncoded("SHIPTOSTATE", payment.getShippingAddress().getStateCode()); npvs.addEncoded("SHIPTOZIP", payment.getShippingAddress().getStateCode()); npvs.addEncoded("SHIPTOCOUNTRY", payment.getShippingAddress().getCountryCode()); } return npvs; }
From source file:com.benfante.minimark.blo.ResultCalculationBo.java
private void evaluateClosedQuestion(ClosedQuestionFilling closedQuestionFilling, String evaluationType, BigDecimal minimumEvaluation) { BigDecimal result = new BigDecimal("0.00"); if (evaluationType == null || Assessment.EVALUATION_CLOSED_SUM_CORRECT_MINUS_WRONG_ANSWERS.equals(evaluationType)) { final BigDecimal weightCorrect = closedQuestionFilling.weightCorrectAnswers(); final BigDecimal weightSelectedCorrect = closedQuestionFilling.weightSelectedCorrectAnswers(); final BigDecimal weightWrong = closedQuestionFilling.weightWrongAnswers(); final BigDecimal weightSelectedWrong = closedQuestionFilling.weightSelectedWrongAnswers(); BigDecimal normalizedCorrect = new BigDecimal("1.00"); if (!BigDecimal.ZERO.equals(weightCorrect)) { // nc = #selectedCorrect/#correct normalizedCorrect = weightSelectedCorrect.divide(weightCorrect, 2, RoundingMode.HALF_EVEN); }/* w w w .j av a 2 s . co m*/ BigDecimal normalizedWrong = new BigDecimal("1.00"); if (!BigDecimal.ZERO.equals(weightWrong)) { // nw = #selectedWrong/#wrong normalizedWrong = weightSelectedWrong.divide(weightWrong, 2, RoundingMode.HALF_EVEN); } // r = nc-nw result = normalizedCorrect.subtract(normalizedWrong); } else if (Assessment.EVALUATION_CLOSED_SUM_CORRECT_ANSWERS.equals(evaluationType)) { final BigDecimal weightCorrect = closedQuestionFilling.weightCorrectAnswers(); final BigDecimal weightSelectedCorrect = closedQuestionFilling.weightSelectedCorrectAnswers(); result = new BigDecimal("1.00"); if (!BigDecimal.ZERO.equals(weightCorrect)) { // r = #selectedCorrect/#correct result = weightSelectedCorrect.divide(weightCorrect, 2, RoundingMode.HALF_EVEN); } } // r = max(r, minimumEvaluation) if (minimumEvaluation != null) { result = result.max(minimumEvaluation); } closedQuestionFilling.setMark(result); }
From source file:es.juntadeandalucia.panelGestion.negocio.vo.TaskVO.java
private void updateCSVProgress(BigDecimal totalSize) { if (taskEntity.getState().getStatus() == Status.FINISHED) { finishState();// w w w . j av a2s .co m } else { // gets current data int readLines = fileProcessor.getNumCurrentEntry() + 1; long readBytes = fileProcessor.getReadBytes(); // calculates the current process BigDecimal readBytesBD = BigDecimal.valueOf(readBytes); double progress = readBytesBD.divide(totalSize, 4, RoundingMode.HALF_UP) .multiply(BigDecimal.valueOf(100)).doubleValue(); // updates the task state taskEntity.getState().setReadLines(readLines); taskEntity.getState().setProgress(progress); // finishes when all bytes were read if (readBytesBD.longValue() == totalSize.longValue()) { finishState(); } } }
From source file:es.juntadeandalucia.panelGestion.negocio.vo.TaskVO.java
private void updateShapeProgress(BigDecimal numFeatures) { if (taskEntity.getState().getStatus() == Status.FINISHED) { finishState();/* w w w .ja va2 s . c o m*/ } else { // gets current data int readLines = fileProcessor.getNumCurrentEntry(); int currentNumFeature = fileProcessor.getNumCurrentEntry(); // calculates the progress BigDecimal currentNumFeatureBD = BigDecimal.valueOf(currentNumFeature); double progress = currentNumFeatureBD.divide(numFeatures, 4, RoundingMode.HALF_UP) .multiply(BigDecimal.valueOf(100)).doubleValue(); // updates the task state taskEntity.getState().setReadLines(readLines); taskEntity.getState().setProgress(progress); // finishes when all bytes are read if (currentNumFeatureBD.longValue() == numFeatures.longValue()) { finishState(); } } }
From source file:org.egov.egf.web.actions.budget.BudgetSearchAction.java
public String divideAndRoundBigDecToString(final BigDecimal amount) { BigDecimal value = amount; value = value.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP); return value.toString(); }
From source file:pyromaniac.Algorithm.QuinceOUFrequencyTable.java
public void loadProbabilities(String probFile) { try {/*from w ww. ja v a2s . c o m*/ URL url = getClass().getResource(probFile); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String header = in.readLine(); if (header.split(",").length != 4) { throw new Exception("Call probabilities does not have four columns as expected"); } String line = in.readLine(); while (line != null) { String[] fields = line.split(","); int mode = Integer.parseInt(fields[0]); BigDecimal lessThan = new BigDecimal(fields[1]).setScale(SCALE, BigDecimal.ROUND_HALF_UP); BigDecimal equalTo = new BigDecimal(fields[2]).setScale(SCALE, BigDecimal.ROUND_HALF_UP); BigDecimal moreThan = new BigDecimal(fields[3]).setScale(SCALE, BigDecimal.ROUND_HALF_UP); BigDecimal sum = lessThan.add(equalTo).add(moreThan).setScale(SCALE, BigDecimal.ROUND_HALF_UP); if (!sum.equals(new BigDecimal("1").setScale(SCALE, BigDecimal.ROUND_HALF_UP))) { lessThan = lessThan.divide(sum, SCALE, BigDecimal.ROUND_HALF_UP); equalTo = equalTo.divide(sum, SCALE, BigDecimal.ROUND_HALF_UP); moreThan = moreThan.divide(sum, SCALE, BigDecimal.ROUND_HALF_UP); } BigDecimal[] probs = { lessThan, equalTo, moreThan }; this.probabilities.put(mode, probs); line = in.readLine(); } } catch (NumberFormatException nfe) { nfe.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }