List of usage examples for java.math BigDecimal multiply
public BigDecimal multiply(BigDecimal multiplicand)
(this × multiplicand)
, and whose scale is (this.scale() + multiplicand.scale()) . From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Multiply and round./* w w w. j a v a 2 s. c o m*/ * * @param x The left factor. * @param n The right factor. * @return the product x*n */ static public BigDecimal multiplyRound(final BigDecimal x, final BigInteger n) { BigDecimal resul = x.multiply(new BigDecimal(n)); /* The estimation of the absolute error in the result is |n*err(x)| */ MathContext mc = new MathContext(n.compareTo(BigInteger.ZERO) != 0 ? x.precision() : 0); return resul.round(mc); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Multiply and round./*from ww w.ja v a 2 s . c o m*/ * * @param x The left factor. * @param y The right factor. * @return The product x*y. */ static public BigDecimal multiplyRound(final BigDecimal x, final BigDecimal y) { BigDecimal resul = x.multiply(y); /* The estimation of the relative error in the result is the sum of the relative * errors |err(y)/y|+|err(x)/x| */ MathContext mc = new MathContext(Math.min(x.precision(), y.precision())); return resul.round(mc); }
From source file:org.kuali.ole.select.document.OleVendorCreditMemoDocument.java
@Override public void processAfterRetrieve() { super.processAfterRetrieve(); try {/*from w w w . j a v a2 s . co m*/ if (this.getVendorAliasName() == null) { populateVendorAliasName(); } Map purchaseOrderTypeIdMap = new HashMap(); if (this.getPurchaseOrderTypeId() != null) { purchaseOrderTypeIdMap.put("purchaseOrderTypeId", this.getPurchaseOrderTypeId()); List<PurchaseOrderType> purchaseOrderTypeDocumentList = (List) getBusinessObjectService() .findMatching(PurchaseOrderType.class, purchaseOrderTypeIdMap); if (purchaseOrderTypeDocumentList != null && purchaseOrderTypeDocumentList.size() > 0) { PurchaseOrderType purchaseOrderTypeDoc = purchaseOrderTypeDocumentList.get(0); this.setOrderType(purchaseOrderTypeDoc); } } List<BigDecimal> newUnitPriceList = new ArrayList<BigDecimal>(); BigDecimal newUnitPrice = new BigDecimal(0); BigDecimal hundred = new BigDecimal(100); List<OleCreditMemoItem> item = this.getItems(); for (int i = 0; item.size() > i; i++) { OleCreditMemoItem items = (OleCreditMemoItem) this.getItem(i); if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) { newUnitPrice = items.getItemUnitPrice().abs(); if (items.getItemUnitPrice() != null && items.getExtendedPrice() != null) { items.setItemSurcharge(items.getExtendedPrice().bigDecimalValue() .subtract(newUnitPrice.multiply(items.getItemQuantity().bigDecimalValue())) .setScale(4, RoundingMode.HALF_UP)); } else { items.setItemSurcharge(BigDecimal.ZERO); } } } if (this.getVendorDetail().getCurrencyType() != null) { if (this.getVendorDetail().getCurrencyType().getCurrencyType() .equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) { currencyTypeIndicator = true; } else { currencyTypeIndicator = false; } } if (this.getVendorDetail() != null && (!currencyTypeIndicator)) { Long currencyTypeId = this.getVendorDetail().getCurrencyType().getCurrencyTypeId(); Map documentNumberMap = new HashMap(); documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId); List<OleExchangeRate> exchangeRateList = (List) getBusinessObjectService().findMatchingOrderBy( OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false); Iterator iterator = exchangeRateList.iterator(); for (OleCreditMemoItem items : item) { iterator = exchangeRateList.iterator(); if (iterator.hasNext()) { OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next(); items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate())); } } } List<OleCreditMemoItem> items = this.getItems(); String itemDescription = ""; for (OleCreditMemoItem singleItem : items) { if (LOG.isDebugEnabled()) { LOG.debug("Title id while retriving ------>" + singleItem.getItemTitleId()); } if (singleItem.getItemTitleId() != null) { /* LOG.debug("###########inside processAfterRetrieve ole credit memo item###########"); HashMap<String, String> queryMap = new HashMap<String, String>(); queryMap.put(OleSelectConstant.DocStoreDetails.ITEMLINKS_KEY, singleItem.getItemTitleId()); List<DocInfoBean> docStoreResult = getBibInfoWrapperService().searchBibInfo(queryMap); Iterator bibIdIterator = docStoreResult.iterator(); if (bibIdIterator.hasNext()) { DocInfoBean docInfoBean = (DocInfoBean) bibIdIterator.next(); if (docInfoBean.getBibIdentifier() == null) { singleItem.setBibUUID(docInfoBean.getUniqueId()); } else { singleItem.setBibUUID(docInfoBean.getBibIdentifier()); } }*/ Bib bib = new BibMarc(); DocstoreClientLocator docstoreClientLocator = new DocstoreClientLocator(); if (singleItem.getItemTitleId() != null && singleItem.getItemTitleId() != "") { bib = docstoreClientLocator.getDocstoreClient().retrieveBib(singleItem.getItemTitleId()); singleItem.setBibUUID(bib.getId()); singleItem .setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(singleItem.getItemTitleId())); } itemDescription = ((bib.getTitle() != null && !bib.getTitle().isEmpty()) ? bib.getTitle() + "," : "") + ((bib.getAuthor() != null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + "," : "") + ((bib.getPublisher() != null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + "," : "") + ((bib.getIsbn() != null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + "," : ""); if (!itemDescription.isEmpty()) { itemDescription = itemDescription.lastIndexOf(",") < 0 ? itemDescription : itemDescription.substring(0, itemDescription.lastIndexOf(",")); } StringEscapeUtils stringEscapeUtils = new StringEscapeUtils(); itemDescription = stringEscapeUtils.unescapeXml(itemDescription); singleItem.setItemDescription(itemDescription); } } if (this.getProrateBy() != null) { this.setProrateQty(this.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)); this.setProrateManual(this.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)); this.setProrateDollar(this.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)); this.setNoProrate(this.getProrateBy().equals(OLEConstants.NO_PRORATE)); } } catch (Exception e) { LOG.error("Exception in OleVendorCreditMemoDocument:processAfterRetrieve " + e); throw new RuntimeException(e); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The hyperbolic tangent./*from w ww .j a va 2 s.com*/ * * @param x The argument. * @return The tanh(x) = sinh(x)/cosh(x). */ static public BigDecimal tanh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return tanh(x.negate()).negate(); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { BigDecimal xhighpr = scalePrec(x, 2); /* tanh(x) = (1-e^(-2x))/(1+e^(-2x)) . */ BigDecimal exp2x = exp(xhighpr.multiply(new BigDecimal(-2))); /* The error in tanh x is err(x)/cosh^2(x). */ double eps = 0.5 * x.ulp().doubleValue() / Math.pow(Math.cosh(x.doubleValue()), 2.0); MathContext mc = new MathContext(err2prec(Math.tanh(x.doubleValue()), eps)); return BigDecimal.ONE.subtract(exp2x).divide(BigDecimal.ONE.add(exp2x), mc); } }
From source file:org.kuali.coeus.common.budget.impl.calculator.SalaryCalculator.java
private ScaleTwoDecimal getPrevSalaryBase(BudgetPerson budgetPerson, Boundary boundary) { Date p1StartDate = budget.getBudgetPeriods().get(0).getStartDate(); BudgetPerson newBudgetPerson = budgetPerson; for (BudgetPerson budgetPerson1 : budget.getBudgetPersons()) { if (((budgetPerson1.getPersonId() != null && budgetPerson1.getPersonId().equals(budgetPerson.getPersonId())) || (budgetPerson1.getRolodexId() != null && budgetPerson1.getRolodexId().equals(budgetPerson.getRolodexId())) || (budgetPerson1.getTbnId() != null && budgetPerson1.getTbnId().equals(budgetPerson.getTbnId()))) && !budgetPerson1.getPersonSequenceNumber().equals(newBudgetPerson.getPersonSequenceNumber()) && budgetPerson1.getJobCode() != null && budgetPerson1.getJobCode().equals(newBudgetPerson.getJobCode()) && budgetPerson1.getEffectiveDate().after(newBudgetPerson.getEffectiveDate()) && budgetPerson1.getEffectiveDate().compareTo(boundary.getStartDate()) <= 0) { newBudgetPerson = budgetPerson1; }/*from ww w . ja v a2 s . com*/ } BigDecimal calBase = newBudgetPerson.getCalculationBase().bigDecimalValue(); if (budgetPerson.getEffectiveDate().before(p1StartDate)) { p1StartDate = budgetPerson.getEffectiveDate(); } QueryList<BudgetRate> qlist = filterInflationRates(p1StartDate, startDate); for (BudgetRate budgetProposalrate : qlist) { if (budgetProposalrate.getStartDate().after(budgetPerson.getEffectiveDate()) && budgetProposalrate.getStartDate().before(startDate)) { calBase = calBase.add(calBase.multiply(budgetProposalrate.getApplicableRate().bigDecimalValue()) .divide(new ScaleTwoDecimal(100.00).bigDecimalValue(), RoundingMode.HALF_UP)); } } return new ScaleTwoDecimal(calBase); }
From source file:com.mb.ext.web.controller.UserController.java
/** * //from w w w . j a v a 2 s.c o m * get news * */ @RequestMapping(value = "/pay", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public ResultDTO pay(@RequestBody PayDTO payDTO, HttpServletRequest request) { ResultDTO resultDTO = new ResultDTO(); PayRequest payRequest = new PayRequest(); payRequest.setAppid(WechatConstants.APPID_VALUE); payRequest.setMch_id(WechatConstants.MERCHANT_ID); payRequest.setNonce_str(RandomStringUtils.randomAlphanumeric(32)); payRequest.setOut_trade_no(payDTO.getOut_trade_no()); try { OrderDTO orderDTO = userService.getOrderByNumber(payDTO.getOut_trade_no()); String productName = orderDTO.getProductName(); BigDecimal amount = orderDTO.getPreAmount(); payRequest.setBody(productName); payRequest.setTotal_fee(amount.multiply(new BigDecimal(100)).intValue()); payRequest.setSpbill_create_ip(request.getRemoteAddr()); payRequest.setNotify_url(WechatConstants.NOTIFY_URL); payRequest.setTrade_type("APP"); payRequest.setAttach("ZHONGHUANBO"); } catch (Exception e) { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } payRequest.setSign(getSign(payRequest)); //xml XStream xstreamRes = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // CDATA boolean cdata = true; @SuppressWarnings("rawtypes") public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }); XStream xstreamReq = new XStream(new XppDriver() /*{ public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // CDATA boolean cdata = true; @SuppressWarnings("rawtypes") public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }*/); xstreamReq.alias("xml", payRequest.getClass()); String requestXML = xstreamReq.toXML(payRequest).replace("\n", "").replace("__", "_"); try { requestXML = new String(requestXML.getBytes("utf-8"), "iso-8859-1"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // BufferedReader reader = null; InputStream is = null; DataOutputStream out = null; StringBuffer sbf = new StringBuffer(); String wechatResponseStr = ""; try { URL url = new URL(WechatConstants.UNIFIED_ORDER_URL); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(requestXML); out.flush(); is = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String strRead = null; while ((strRead = reader.readLine()) != null) { sbf.append(strRead); sbf.append("\r\n"); } wechatResponseStr = sbf.toString(); } catch (Exception e) { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } finally { try { reader.close(); is.close(); out.close(); } catch (IOException e) { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } } //? xstreamRes.alias("xml", PayResponse.class); PayResponse payResponse = (PayResponse) xstreamRes.fromXML(wechatResponseStr); //MOCK MODE /*PayResponse payResponse = new PayResponse(); payResponse.setPrepay_id("WX123456789009876543211234567890"); payResponse.setMch_id("6749328409382943"); payResponse.setNonce_str("764932874987392"); payResponse.setTrade_type("APP"); payResponse.setReturn_code("SUCCESS"); payResponse.setResult_code("SUCCESS");*/ if ("SUCCESS".equals(payResponse.getReturn_code()) && "SUCCESS".equals(payResponse.getResult_code())) { payDTO.setMch_id(payResponse.getMch_id()); payDTO.setNonce_str(payResponse.getNonce_str()); payDTO.setPrepay_id(payResponse.getPrepay_id()); payDTO.setTrade_type(payResponse.getTrade_type()); payDTO.setTimestamp(String.valueOf(System.currentTimeMillis() / 1000)); payDTO.setSign(getSignForClient(payDTO)); resultDTO.setBody(payDTO); resultDTO.setCode("0"); resultDTO.setMessage("??"); } else { resultDTO.setCode("1"); resultDTO.setMessage("?"); return resultDTO; } return resultDTO; }
From source file:org.egov.wtms.service.es.WaterChargeElasticSearchService.java
/** * Returns Top Ten with ULB wise grouping and total amount aggregation * * @param waterChargedashBoardRequest/*w w w .j ava 2 s .co m*/ * @param indexName * @param order * @param orderingAggregationName * @return */ public List<WaterTaxPayerDetails> returnUlbWiseAggregationResults( final WaterChargeDashBoardRequest waterChargedashBoardRequest, final String indexName, final Boolean order, final String orderingAggregationName, final int size, final boolean isBillCollectorWise) { final List<WaterTaxPayerDetails> taxPayers = new ArrayList<>(); Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>(); final BoolQueryBuilder boolQuery = waterChargeCollDocService.prepareWhereClause(waterChargedashBoardRequest, null); CFinancialYear currFinYear = cFinancialYearService.getCurrentFinancialYear(); // orderingAggregationName is the aggregation name by which we have to // order the results // IN this case can be one of "totaldemand" or TOTAL_COLLECTION or // "avg_achievement" String groupingField; if (StringUtils.isNotBlank(waterChargedashBoardRequest.getUlbCode()) || StringUtils .isNotBlank(waterChargedashBoardRequest.getType()) && (waterChargedashBoardRequest.getType().equals(DASHBOARD_GROUPING_WARDWISE) || waterChargedashBoardRequest.getType().equals(DASHBOARD_GROUPING_BILLCOLLECTORWISE))) groupingField = WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD; else groupingField = WaterTaxConstants.CITYNAMEAGGREGATIONFIELD; Long startTime = System.currentTimeMillis(); @SuppressWarnings("rawtypes") AggregationBuilder aggregation; SearchQuery searchQueryColl; // Apply the ordering and max results size only if the type is not // billcollector if (!isBillCollectorWise) { aggregation = AggregationBuilders.terms(AGGREGATION_FIELD).field(groupingField).size(size) .order(Terms.Order.aggregation(orderingAggregationName, order)) .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND)) .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field("totalCollection")); searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery) .addAggregation(aggregation).build(); } else { aggregation = AggregationBuilders.terms(AGGREGATION_FIELD).field(groupingField).size(250) .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND)) .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field("totalCollection")); searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery) .withPageable(new PageRequest(0, 250)).addAggregation(aggregation).build(); } final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl, response -> response.getAggregations()); // Fetch ward wise Bill Collector details for ward based grouping if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(waterChargedashBoardRequest.getType())) wardWiseBillCollectors = waterChargeCollDocService .getWardWiseBillCollectors(waterChargedashBoardRequest); Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by ulbWiseAggregations is (millisecs) : " + timeTaken); WaterTaxPayerDetails taxDetail; startTime = System.currentTimeMillis(); final Date fromDate = DateUtils.startOfDay(currFinYear.getStartingDate()); final Date toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); final Date lastYearFromDate = org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1); final Date lastYearToDate = org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1); final StringTerms totalAmountAggr = collAggr.get(AGGREGATION_FIELD); for (final Terms.Bucket entry : totalAmountAggr.getBuckets()) { taxDetail = new WaterTaxPayerDetails(); taxDetail.setRegionName(waterChargedashBoardRequest.getRegionName()); taxDetail.setDistrictName(waterChargedashBoardRequest.getDistrictName()); taxDetail.setUlbGrade(waterChargedashBoardRequest.getUlbGrade()); final String fieldName = String.valueOf(entry.getKey()); if (groupingField.equals(WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD)) { taxDetail.setWardName(fieldName); if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(waterChargedashBoardRequest.getType()) && !wardWiseBillCollectors.isEmpty()) taxDetail.setBillCollector(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY : wardWiseBillCollectors.get(fieldName).getBillCollector()); } else taxDetail.setUlbName(fieldName); // Proportional Demand = (totalDemand/12)*noOfmonths final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1; final Sum totalDemandAggregation = entry.getAggregations().get(TOTALDEMAND); final Sum totalCollectionAggregation = entry.getAggregations().get(TOTAL_COLLECTION); final BigDecimal totalDemandValue = BigDecimal.valueOf(totalDemandAggregation.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP); final BigDecimal totalCollections = BigDecimal.valueOf(totalCollectionAggregation.getValue()) .setScale(0, BigDecimal.ROUND_HALF_UP); final BigDecimal proportionalDemand = totalDemandValue .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths)); taxDetail.setTotalDmd(totalDemandValue); taxDetail.setCurrentYearTillDateColl(totalCollections); taxDetail.setCurrentYearTillDateDmd(proportionalDemand); taxDetail.setAchievement(totalCollections.multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP)); taxDetail.setCurrentYearTillDateBalDmd(proportionalDemand.subtract(totalCollections)); final BigDecimal lastYearCollection = waterChargeCollDocService.getCollectionBetweenDates( waterChargedashBoardRequest, lastYearFromDate, lastYearToDate, fieldName); // variance = ((lastYearCollection/currentYearCollection )*100) BigDecimal variation = BigDecimal.ZERO; taxDetail.setLastYearTillDateColl(lastYearCollection); if (lastYearCollection.compareTo(BigDecimal.ZERO) == 0) variation = WaterTaxConstants.BIGDECIMAL_100; else if (totalCollections.compareTo(BigDecimal.ZERO) > 0) variation = taxDetail.getCurrentYearTillDateColl().subtract(taxDetail.getLastYearTillDateColl()) .multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(taxDetail.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP); /* * variation * =taxDetail.getLastYearTillDateColl().multiply(WaterTaxConstants. * BIGDECIMAL_100) .divide(totalCollections, 1, * BigDecimal.ROUND_HALF_UP); */ taxDetail.setLastYearVar(variation); taxPayers.add(taxDetail); } timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken for setting values in returnUlbWiseAggregationResults() is (millisecs) : " + timeTaken); return returnTopResults(taxPayers, size, order); }
From source file:org.kuali.kfs.module.bc.document.service.impl.SalarySettingServiceImpl.java
/** * @see org.kuali.kfs.module.bc.document.service.SalarySettingService#calculateHourlyPayRate(org.kuali.kfs.module.bc.businessobject.PendingBudgetConstructionAppointmentFunding) *//*ww w. java 2 s . c om*/ public BigDecimal calculateHourlyPayRate(PendingBudgetConstructionAppointmentFunding appointmentFunding) { LOG.debug("calculateHourlyPayRate() start"); KualiInteger requestedAmount = appointmentFunding.getAppointmentRequestedAmount(); BigDecimal fteQuantity = this.calculateFteQuantityFromAppointmentFunding(appointmentFunding); BigDecimal annualWorkingHours = BigDecimal.valueOf(BudgetParameterFinder.getAnnualWorkingHours()); BigDecimal totalPayHoursForYear = fteQuantity.multiply(annualWorkingHours); BigDecimal hourlyPayRate = BigDecimal.ZERO; if (totalPayHoursForYear.compareTo(BigDecimal.ZERO) != 0) { hourlyPayRate = requestedAmount.divide(totalPayHoursForYear).setScale(2, BigDecimal.ROUND_HALF_UP); } return hourlyPayRate; }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The natural logarithm./*from w ww . j a v a2 s .c o m*/ * * @param n The main argument, a strictly positive integer. * @param mc The requirements on the precision. * @return ln(n). */ static public BigDecimal log(int n, final MathContext mc) { /* the value is undefined if x is negative. */ if (n <= 0) { throw new ArithmeticException("Cannot take log of negative " + n); } else if (n == 1) { return BigDecimal.ZERO; } else if (n == 2) { if (mc.getPrecision() < LOG2.precision()) { return LOG2.round(mc); } else { /* Broadhurst \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067} * Error propagation: the error in log(2) is twice the error in S(2,-5,...). */ int[] a = { 2, -5, -2, -7, -2, -5, 2, -3 }; BigDecimal S = broadhurstBBP(2, 1, a, new MathContext(1 + mc.getPrecision())); S = S.multiply(new BigDecimal(8)); S = sqrt(divideRound(S, 3)); return S.round(mc); } } else if (n == 3) { /* summation of a series roughly proportional to (7/500)^k. Estimate count * of terms to estimate the precision (drop the favorable additional * 1/k here): 0.013^k <= 10^(-precision), so k*log10(0.013) <= -precision * so k>= precision/1.87. */ int kmax = (int) (mc.getPrecision() / 1.87); MathContext mcloc = new MathContext(mc.getPrecision() + 1 + (int) (Math.log10(kmax * 0.693 / 1.098))); BigDecimal log3 = multiplyRound(log(2, mcloc), 19); /* log3 is roughly 1, so absolute and relative error are the same. The * result will be divided by 12, so a conservative error is the one * already found in mc */ double eps = prec2err(1.098, mc.getPrecision()) / kmax; Rational r = new Rational(7153, 524288); Rational pk = new Rational(7153, 524288); for (int k = 1;; k++) { Rational tmp = pk.divide(k); if (tmp.doubleValue() < eps) { break; } /* how many digits of tmp do we need in the sum? */ mcloc = new MathContext(err2prec(tmp.doubleValue(), eps)); BigDecimal c = pk.divide(k).BigDecimalValue(mcloc); if (k % 2 != 0) { log3 = log3.add(c); } else { log3 = log3.subtract(c); } pk = pk.multiply(r); } log3 = divideRound(log3, 12); return log3.round(mc); } else if (n == 5) { /* summation of a series roughly proportional to (7/160)^k. Estimate count * of terms to estimate the precision (drop the favorable additional * 1/k here): 0.046^k <= 10^(-precision), so k*log10(0.046) <= -precision * so k>= precision/1.33. */ int kmax = (int) (mc.getPrecision() / 1.33); MathContext mcloc = new MathContext(mc.getPrecision() + 1 + (int) (Math.log10(kmax * 0.693 / 1.609))); BigDecimal log5 = multiplyRound(log(2, mcloc), 14); /* log5 is roughly 1.6, so absolute and relative error are the same. The * result will be divided by 6, so a conservative error is the one * already found in mc */ double eps = prec2err(1.6, mc.getPrecision()) / kmax; Rational r = new Rational(759, 16384); Rational pk = new Rational(759, 16384); for (int k = 1;; k++) { Rational tmp = pk.divide(k); if (tmp.doubleValue() < eps) { break; } /* how many digits of tmp do we need in the sum? */ mcloc = new MathContext(err2prec(tmp.doubleValue(), eps)); BigDecimal c = pk.divide(k).BigDecimalValue(mcloc); log5 = log5.subtract(c); pk = pk.multiply(r); } log5 = divideRound(log5, 6); return log5.round(mc); } else if (n == 7) { /* summation of a series roughly proportional to (1/8)^k. Estimate count * of terms to estimate the precision (drop the favorable additional * 1/k here): 0.125^k <= 10^(-precision), so k*log10(0.125) <= -precision * so k>= precision/0.903. */ int kmax = (int) (mc.getPrecision() / 0.903); MathContext mcloc = new MathContext( mc.getPrecision() + 1 + (int) (Math.log10(kmax * 3 * 0.693 / 1.098))); BigDecimal log7 = multiplyRound(log(2, mcloc), 3); /* log7 is roughly 1.9, so absolute and relative error are the same. */ double eps = prec2err(1.9, mc.getPrecision()) / kmax; Rational r = new Rational(1, 8); Rational pk = new Rational(1, 8); for (int k = 1;; k++) { Rational tmp = pk.divide(k); if (tmp.doubleValue() < eps) { break; } /* how many digits of tmp do we need in the sum? */ mcloc = new MathContext(err2prec(tmp.doubleValue(), eps)); BigDecimal c = pk.divide(k).BigDecimalValue(mcloc); log7 = log7.subtract(c); pk = pk.multiply(r); } return log7.round(mc); } else { /* At this point one could either forward to the log(BigDecimal) signature (implemented) * or decompose n into Ifactors and use an implemenation of all the prime bases. * Estimate of the result; convert the mc argument to an absolute error eps * log(n+errn) = log(n)+errn/n = log(n)+eps */ double res = Math.log((double) n); double eps = prec2err(res, mc.getPrecision()); /* errn = eps*n, convert absolute error in result to requirement on absolute error in input */ eps *= n; /* Convert this absolute requirement of error in n to a relative error in n */ final MathContext mcloc = new MathContext(1 + err2prec((double) n, eps)); /* Padd n with a number of zeros to trigger the required accuracy in * the standard signature method */ BigDecimal nb = scalePrec(new BigDecimal(n), mcloc); return log(nb); } }
From source file:org.libreplan.web.planner.order.OrderPlanningModel.java
private String getLabelTextEarnedValueType(OrderEarnedValueChartFiller earnedValueChartFiller, EarnedValueType type, LocalDate date) { BigDecimal value = earnedValueChartFiller.getIndicator(type, date); String units = _("h"); if (type.equals(EarnedValueType.CPI) || type.equals(EarnedValueType.SPI)) { value = value.multiply(new BigDecimal(100)); units = "%"; }//from w w w . j a v a 2 s .c o m return value.setScale(0, RoundingMode.HALF_UP) + " " + units; }