List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend, MathContext mc)
From source file:Main.java
public static void main(String[] args) { MathContext mc = new MathContext(2); // 2 precision BigDecimal bg1 = new BigDecimal("100.123"); BigDecimal bg2 = new BigDecimal("50.56"); // subtract bg1 with bg2 using mc and assign result to bg3 BigDecimal bg3 = bg1.subtract(bg2, mc); String str = "The Result of Subtraction is " + bg3; // print bg3 value System.out.println(str);/*from ww w .j a v a 2 s .c o m*/ }
From source file:Main.java
public static BigDecimal cuberoot(BigDecimal b) { // Specify a math context with 40 digits of precision. MathContext mc = new MathContext(40); BigDecimal x = new BigDecimal("1", mc); // Search for the cube root via the Newton-Raphson loop. Output each // successive iteration's value. for (int i = 0; i < ITER; i++) { x = x.subtract( x.pow(3, mc).subtract(b, mc).divide(new BigDecimal("3", mc).multiply(x.pow(2, mc), mc), mc), mc);/* ww w. jav a2 s . c om*/ } return x; }
From source file:Main.java
public static BigDecimal cuberoot(BigDecimal b) { // Specify a math context with 40 digits of precision. MathContext mc = new MathContext(40); BigDecimal x = new BigDecimal("1", mc); // Search for the cube root via the Newton-Raphson loop. Output each // // successive iteration's value. for (int i = 0; i < ITER; i++) { x = x.subtract( x.pow(3, mc).subtract(b, mc).divide(new BigDecimal("3", mc).multiply(x.pow(2, mc), mc), mc), mc);/*from w w w. j ava 2 s . co m*/ } return x; }
From source file:com.qcadoo.mes.masterOrders.hooks.OrderDetailsHooksMO.java
private void fillMasterOrderFields(final ViewDefinitionState view, final Entity masterOrder, final Entity product) { FieldComponent numberField = (FieldComponent) view.getComponentByReference(OrderFields.NUMBER); LookupComponent companyLookup = (LookupComponent) view.getComponentByReference(OrderFields.COMPANY); FieldComponent deadlineField = (FieldComponent) view.getComponentByReference(OrderFields.DEADLINE); FieldComponent dateFromField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_FROM); FieldComponent dateToField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_TO); LookupComponent productLookup = (LookupComponent) view.getComponentByReference(OrderFields.PRODUCT); LookupComponent technologyPrototypeLookup = (LookupComponent) view .getComponentByReference(OrderFields.TECHNOLOGY_PROTOTYPE); FieldComponent plannedQuantityField = (FieldComponent) view .getComponentByReference(OrderFields.PLANNED_QUANTITY); if (masterOrder != null) { String masterOrderNumber = masterOrder.getStringField(MasterOrderFields.NUMBER); Entity masterOrderCompany = masterOrder.getBelongsToField(MasterOrderFields.COMPANY); Date masterOrderDeadline = masterOrder.getDateField(MasterOrderFields.DEADLINE); Date masterOrderStartDate = masterOrder.getDateField(MasterOrderFields.START_DATE); Date masterOrderFinishDate = masterOrder.getDateField(MasterOrderFields.FINISH_DATE); Entity masterOrderProduct = masterOrder.getBelongsToField(MasterOrderFields.PRODUCT); BigDecimal masterOrderQuantity = BigDecimalUtils .convertNullToZero(masterOrder.getDecimalField(MasterOrderFields.MASTER_ORDER_QUANTITY)); BigDecimal cumulatedOrderQuantity = BigDecimalUtils.convertNullToZero(masterOrderOrdersDataProvider .sumBelongingOrdersPlannedQuantities(masterOrder, masterOrderProduct)); BigDecimal plannedQuantity = masterOrderQuantity.subtract(cumulatedOrderQuantity, numberService.getMathContext()); if (product != null) { masterOrderProduct = product; }/*from w ww . ja v a 2 s.com*/ Entity masterOrderTechnology = masterOrder.getBelongsToField(MasterOrderFields.TECHNOLOGY); String number = (String) numberField.getFieldValue(); String generatedNumber = numberGeneratorService.generateNumberWithPrefix( OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER, 3, masterOrderNumber + "-"); // if (StringUtils.isEmpty(number) || generatedNumber.equals(number)) { numberField.setFieldValue(generatedNumber); // } if ((companyLookup.getEntity() == null) && (masterOrderCompany != null)) { companyLookup.setFieldValue(masterOrderCompany.getId()); } if (StringUtils.isEmpty((String) deadlineField.getFieldValue()) && (masterOrderDeadline != null)) { deadlineField.setFieldValue(DateUtils.toDateTimeString(masterOrderDeadline)); } if (StringUtils.isEmpty((String) dateFromField.getFieldValue()) && (masterOrderStartDate != null)) { dateFromField.setFieldValue(DateUtils.toDateTimeString(masterOrderStartDate)); } if (StringUtils.isEmpty((String) dateToField.getFieldValue()) && (masterOrderFinishDate != null)) { dateToField.setFieldValue(DateUtils.toDateTimeString(masterOrderFinishDate)); } if ((productLookup.getEntity() == null) && (masterOrderProduct != null)) { productLookup.setFieldValue(masterOrderProduct.getId()); } if ((technologyPrototypeLookup.getEntity() == null) && (masterOrderTechnology != null)) { technologyPrototypeLookup.setFieldValue(masterOrderTechnology.getId()); } if (StringUtils.isEmpty((String) plannedQuantityField.getFieldValue()) && (plannedQuantity != null) && (BigDecimal.ZERO.compareTo(plannedQuantity) < 0)) { plannedQuantityField.setFieldValue(numberService.format(plannedQuantity)); } numberField.requestComponentUpdateState(); companyLookup.requestComponentUpdateState(); deadlineField.requestComponentUpdateState(); dateFromField.requestComponentUpdateState(); dateToField.requestComponentUpdateState(); productLookup.requestComponentUpdateState(); technologyPrototypeLookup.requestComponentUpdateState(); plannedQuantityField.requestComponentUpdateState(); productLookup.performEvent(view, "onSelectedEntityChange", ""); } }
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.java2s .com } } } 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.nd4j.linalg.util.BigDecimalMath.java
/** * The inverse trigonometric sine./*from w w w . ja va 2 s . co m*/ * * @param x the argument. * @return the arcsin(x) in radians. */ static public BigDecimal asin(final BigDecimal x) { if (x.compareTo(BigDecimal.ONE) > 0 || x.compareTo(BigDecimal.ONE.negate()) < 0) { throw new ArithmeticException("Out of range argument " + x.toString() + " of asin"); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else if (x.compareTo(BigDecimal.ONE) == 0) { /* arcsin(1) = pi/2 */ double errpi = Math.sqrt(x.ulp().doubleValue()); MathContext mc = new MathContext(err2prec(3.14159, errpi)); return pi(mc).divide(new BigDecimal(2)); } else if (x.compareTo(BigDecimal.ZERO) < 0) { return asin(x.negate()).negate(); } else if (x.doubleValue() > 0.7) { final BigDecimal xCompl = BigDecimal.ONE.subtract(x); final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.)); final BigDecimal xhighpr = scalePrec(xCompl, 3); final BigDecimal xhighprV = divideRound(xhighpr, 4); BigDecimal resul = BigDecimal.ONE; /* x^(2i+1) */ BigDecimal xpowi = BigDecimal.ONE; /* i factorial */ BigInteger ifacN = BigInteger.ONE; BigInteger ifacD = BigInteger.ONE; for (int i = 1;; i++) { ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1))); ifacD = ifacD.multiply(new BigInteger("" + i)); if (i == 1) { xpowi = xhighprV; } else { xpowi = multiplyRound(xpowi, xhighprV); } BigDecimal c = divideRound(multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); resul = resul.add(c); /* series started 1+x/12+... which yields an estimate of the sums error */ if (Math.abs(c.doubleValue()) < xUlpDbl / 120.) { break; } } /* sqrt(2*z)*(1+...) */ xpowi = sqrt(xhighpr.multiply(new BigDecimal(2))); resul = multiplyRound(xpowi, resul); MathContext mc = new MathContext(resul.precision()); BigDecimal pihalf = pi(mc).divide(new BigDecimal(2)); mc = new MathContext(err2prec(resul.doubleValue(), eps)); return pihalf.subtract(resul, mc); } else { /* absolute error in the result is err(x)/sqrt(1-x^2) to lowest order */ final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.)); final BigDecimal xhighpr = scalePrec(x, 2); final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr); BigDecimal resul = xhighpr.plus(); /* x^(2i+1) */ BigDecimal xpowi = xhighpr; /* i factorial */ BigInteger ifacN = BigInteger.ONE; BigInteger ifacD = BigInteger.ONE; for (int i = 1;; i++) { ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1))); ifacD = ifacD.multiply(new BigInteger("" + (2 * i))); xpowi = multiplyRound(xpowi, xhighprSq); BigDecimal c = divideRound(multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); resul = resul.add(c); if (Math.abs(c.doubleValue()) < 0.1 * eps) { break; } } MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps)); return resul.round(mc); } }
From source file:com.qcadoo.mes.productionCounting.ProductionCountingServiceImpl.java
@Override public BigDecimal getRegisteredProductValueForOperationProductIn(final Entity operationProduct, final BigDecimal planed) { BigDecimal value = null;// w ww. j a va 2s . co m Entity toc = operationProduct.getBelongsToField(OperationProductInComponentFields.OPERATION_COMPONENT); Entity product = operationProduct.getBelongsToField(OperationProductInComponentFields.PRODUCT); List<Entity> tracings = getProductionTrackingDD().find() .add(SearchRestrictions.belongsTo(ProductionTrackingFields.TECHNOLOGY_OPERATION_COMPONENT, toc)) .add(SearchRestrictions.eq(ProductionTrackingFields.STATE, ProductionTrackingStateStringValues.ACCEPTED)) .list().getEntities(); for (Entity tracking : tracings) { Entity topIN = getTrackingOperationProductInComponentDD().find() .add(SearchRestrictions.belongsTo(TrackingOperationProductInComponentFields.PRODUCTION_TRACKING, tracking)) .add(SearchRestrictions.belongsTo(TrackingOperationProductInComponentFields.PRODUCT, product)) .setMaxResults(1).uniqueResult(); if (topIN != null) { if (value == null) { value = new BigDecimal(0l); } value = value.add(topIN.getDecimalField(TrackingOperationProductInComponentFields.USED_QUANTITY), numberService.getMathContext()); } } if (value != null) { value = planed.subtract(value, numberService.getMathContext()); } else { return value; } if (value.compareTo(new BigDecimal(0l)) == -1) { value = new BigDecimal(0l); } return value; }
From source file:com.qcadoo.mes.productionCounting.ProductionCountingServiceImpl.java
@Override public BigDecimal getRegisteredProductValueForOperationProductOut(final Entity operationProduct, final BigDecimal planed) { BigDecimal value = null;//w w w . j ava2 s .com Entity toc = operationProduct.getBelongsToField(OperationProductOutComponentFields.OPERATION_COMPONENT); Entity product = operationProduct.getBelongsToField(OperationProductOutComponentFields.PRODUCT); List<Entity> tracings = getProductionTrackingDD().find() .add(SearchRestrictions.belongsTo(ProductionTrackingFields.TECHNOLOGY_OPERATION_COMPONENT, toc)) .add(SearchRestrictions.eq(ProductionTrackingFields.STATE, ProductionTrackingStateStringValues.ACCEPTED)) .list().getEntities(); for (Entity tracking : tracings) { Entity topIN = getTrackingOperationProductOutComponentDD().find() .add(SearchRestrictions .belongsTo(TrackingOperationProductOutComponentFields.PRODUCTION_TRACKING, tracking)) .add(SearchRestrictions.belongsTo(TrackingOperationProductOutComponentFields.PRODUCT, product)) .setMaxResults(1).uniqueResult(); if (topIN != null) { if (value == null) { value = new BigDecimal(0l); } value = value.add(topIN.getDecimalField(TrackingOperationProductOutComponentFields.USED_QUANTITY), numberService.getMathContext()); } } if (value != null) { value = planed.subtract(value, numberService.getMathContext()); } else { return value; } if (value.compareTo(new BigDecimal(0l)) == -1) { value = new BigDecimal(0l); } return value; }
From source file:org.kuali.kpme.tklm.time.rules.overtime.weekly.service.WeeklyOvertimeRuleServiceImpl.java
@Override public void processWeeklyOvertimeRule(TimesheetDocument timesheetDocument, TkTimeBlockAggregate aggregate) { LocalDate asOfDate = timesheetDocument.getDocumentHeader().getEndDateTime().toLocalDate(); String principalId = timesheetDocument.getDocumentHeader().getPrincipalId(); DateTime beginDate = timesheetDocument.getDocumentHeader().getBeginDateTime(); DateTime endDate = timesheetDocument.getDocumentHeader().getEndDateTime(); List<WeeklyOvertimeRule> weeklyOvertimeRules = getWeeklyOvertimeRules(asOfDate); List<List<FlsaWeek>> newFlsaWeeks = getFlsaWeeks(principalId, beginDate, endDate, aggregate); for (List<FlsaWeek> flsaWeekParts : newFlsaWeeks) { BigDecimal totalNewOvertimeHours = null; BigDecimal hoursTowardsMaxEarnCodes = null; for (WeeklyOvertimeRule weeklyOvertimeRule : weeklyOvertimeRules) { Set<String> maxHoursEarnCodes = HrServiceLocator.getEarnCodeGroupService() .getEarnCodeListForEarnCodeGroup(weeklyOvertimeRule.getMaxHoursEarnGroup(), asOfDate); Set<String> convertFromEarnCodes = HrServiceLocator.getEarnCodeGroupService() .getEarnCodeListForEarnCodeGroup(weeklyOvertimeRule.getConvertFromEarnGroup(), asOfDate); Set<String> applyToEarnCodes = HrServiceLocator.getEarnCodeGroupService() .getEarnCodeListForEarnCodeGroup(weeklyOvertimeRule.getApplyToEarnGroup(), asOfDate); LOG.info(weeklyOvertimeRule); LOG.info("maxHoursEarnCodes ="); LOG.info(maxHoursEarnCodes); LOG.info("convertFromEarnCodes ="); LOG.info(convertFromEarnCodes); LOG.info("before applying rule"); LOG.info(newFlsaWeeks);//from ww w .jav a2 s . co m /***************/ if (hoursTowardsMaxEarnCodes == null) { hoursTowardsMaxEarnCodes = getHours(flsaWeekParts, maxHoursEarnCodes); } if (totalNewOvertimeHours == null) { totalNewOvertimeHours = hoursTowardsMaxEarnCodes.subtract(weeklyOvertimeRule.getMaxHours(), HrConstants.MATH_CONTEXT); } //flsaWeekParts.get(0).getFlsaDays().get(0).getAppliedTimeBlocks().get(0). BigDecimal thisRuleConvertableHours = getHours(flsaWeekParts, convertFromEarnCodes); LOG.info("maxEarnCodes"); LOG.info(maxHoursEarnCodes); LOG.info("convertTo"); LOG.info(weeklyOvertimeRule.getConvertToEarnCode()); LOG.info("newOverTimeHours"); LOG.info(totalNewOvertimeHours); BigDecimal thisRuleOvertimeHoursToApply = BigDecimal.ZERO; if (thisRuleConvertableHours.compareTo(BigDecimal.ZERO) > 0) { thisRuleOvertimeHoursToApply = totalNewOvertimeHours; if (thisRuleConvertableHours.compareTo(totalNewOvertimeHours) < 0) { thisRuleOvertimeHoursToApply = thisRuleConvertableHours; } } Boolean ruleRan = false; if ((totalNewOvertimeHours.compareTo(BigDecimal.ZERO) > 0) && (thisRuleOvertimeHoursToApply.compareTo(BigDecimal.ZERO) > 0)) { BigDecimal afterOvertimeRuleRanHours = applyOvertimeToFlsaWeeks(flsaWeekParts, weeklyOvertimeRule, asOfDate.plusDays((7 - asOfDate.getDayOfWeek())), applyToEarnCodes, thisRuleOvertimeHoursToApply); totalNewOvertimeHours = totalNewOvertimeHours .subtract(thisRuleOvertimeHoursToApply.subtract(afterOvertimeRuleRanHours)); } LOG.info("ruleRan: " + (ruleRan ? "Y" : "N")); } LOG.info("after applying rule"); LOG.info(newFlsaWeeks); } //convert weeks to list of timeblocks to push back into aggregate List<List<TimeBlock>> updatedBlocks = new ArrayList<List<TimeBlock>>(); DateTime d1 = aggregate.getPayCalendarEntry().getBeginPeriodFullDateTime().minusDays(1); DateTime d2 = aggregate.getPayCalendarEntry().getBatchEndPayPeriodFullDateTime(); Interval calEntryInterval = null; if (d2 != null) { calEntryInterval = new Interval( aggregate.getPayCalendarEntry().getBeginPeriodFullDateTime().minusDays(1), aggregate.getPayCalendarEntry().getEndPeriodFullDateTime().plusDays((7 - aggregate.getPayCalendarEntry().getBatchEndPayPeriodFullDateTime().getDayOfWeek()))); } else { //calEntryInterval = new Interval(d1, aggregate.getPayCalendarEntry().getEndPeriodFullDateTime().plusDays((7 - d2.getDayOfWeek() ) )); calEntryInterval = new Interval( aggregate.getPayCalendarEntry().getBeginPeriodFullDateTime().minusDays(1), aggregate.getPayCalendarEntry().getEndPeriodFullDateTime()); } for (List<FlsaWeek> weekParts : newFlsaWeeks) { for (FlsaWeek week : weekParts) { for (FlsaDay day : week.getFlsaDays()) { if (calEntryInterval.contains(day.getFlsaDate().toDateTime())) { updatedBlocks.add(day.getAppliedTimeBlocks()); } } } } //merge if (aggregate.getDayTimeBlockList().size() - updatedBlocks.size() == 2) { List<TimeBlock> firstDay = aggregate.getDayTimeBlockList().get(0); List<TimeBlock> lastDay = aggregate.getDayTimeBlockList() .get(aggregate.getDayTimeBlockList().size() - 1); updatedBlocks.add(0, firstDay); updatedBlocks.add(lastDay); } aggregate.setDayTimeBlockList(updatedBlocks); //savePreviousNextCalendarTimeBlocks(flsaWeeks); }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private Predicate createPredicateNumeric(CriteriaBuilder builder, IQueryParameterType params, ParamPrefixEnum cmpValue, BigDecimal valueValue, final Expression<BigDecimal> path, String invalidMessageName, String theValueString) { Predicate num;//w w w. j a v a 2s.co m switch (cmpValue) { case GREATERTHAN: num = builder.gt(path, valueValue); break; case GREATERTHAN_OR_EQUALS: num = builder.ge(path, valueValue); break; case LESSTHAN: num = builder.lt(path, valueValue); break; case LESSTHAN_OR_EQUALS: num = builder.le(path, valueValue); break; case APPROXIMATE: case EQUAL: case NOT_EQUAL: BigDecimal mul = calculateFuzzAmount(cmpValue, valueValue); BigDecimal low = valueValue.subtract(mul, MathContext.DECIMAL64); BigDecimal high = valueValue.add(mul, MathContext.DECIMAL64); Predicate lowPred; Predicate highPred; if (cmpValue != ParamPrefixEnum.NOT_EQUAL) { lowPred = builder.ge(path.as(BigDecimal.class), low); highPred = builder.le(path.as(BigDecimal.class), high); num = builder.and(lowPred, highPred); ourLog.trace("Searching for {} <= val <= {}", low, high); } else { // Prefix was "ne", so reverse it! lowPred = builder.lt(path.as(BigDecimal.class), low); highPred = builder.gt(path.as(BigDecimal.class), high); num = builder.or(lowPred, highPred); } break; default: String msg = myContext.getLocalizer().getMessage(SearchBuilder.class, invalidMessageName, cmpValue.getValue(), params.getValueAsQueryToken(myContext)); throw new InvalidRequestException(msg); } return num; }