List of usage examples for java.math BigDecimal precision
int precision
To view the source code for java.math BigDecimal precision.
Click Source Link
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The Gamma function./*from ww w .j a v a 2 s.c o m*/ * * @param x The argument. * @return Gamma(x). */ static public BigDecimal Gamma(final BigDecimal x) { /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33 */ if (x.compareTo(BigDecimal.ZERO) < 0) { return divideRound(Gamma(x.add(BigDecimal.ONE)), x); } else if (x.doubleValue() > 1.5) { /* Gamma(x) = Gamma(xmin+n) = Gamma(xmin)*Pochhammer(xmin,n). */ int n = (int) (x.doubleValue() - 0.5); BigDecimal xmin1 = x.subtract(new BigDecimal(n)); return multiplyRound(Gamma(xmin1), pochhammer(xmin1, n)); } else { /* apply Abramowitz-Stegun 6.1.33 */ BigDecimal z = x.subtract(BigDecimal.ONE); /* add intermediately 2 digits to the partial sum accumulation */ z = scalePrec(z, 2); MathContext mcloc = new MathContext(z.precision()); /* measure of the absolute error is the relative error in the first, logarithmic term */ double eps = x.ulp().doubleValue() / x.doubleValue(); BigDecimal resul = log(scalePrec(x, 2)).negate(); if (x.compareTo(BigDecimal.ONE) != 0) { BigDecimal gammCompl = BigDecimal.ONE.subtract(gamma(mcloc)); resul = resul.add(multiplyRound(z, gammCompl)); for (int n = 2;; n++) { /* multiplying z^n/n by zeta(n-1) means that the two relative errors add. * so the requirement in the relative error of zeta(n)-1 is that this is somewhat * smaller than the relative error in z^n/n (the absolute error of thelatter is the * absolute error in z) */ BigDecimal c = divideRound(z.pow(n, mcloc), n); MathContext m = new MathContext(err2prec(n * z.ulp().doubleValue() / 2. / z.doubleValue())); c = c.round(m); /* At larger n, zeta(n)-1 is roughly 1/2^n. The product is c/2^n. * The relative error in c is c.ulp/2/c . The error in the product should be small versus eps/10. * Error from 1/2^n is c*err(sigma-1). * We need a relative error of zeta-1 of the order of c.ulp/50/c. This is an absolute * error in zeta-1 of c.ulp/50/c/2^n, and also the absolute error in zeta, because zeta is * of the order of 1. */ if (eps / 100. / c.doubleValue() < 0.01) { m = new MathContext(err2prec(eps / 100. / c.doubleValue())); } else { m = new MathContext(2); } /* zeta(n) -1 */ BigDecimal zetm1 = zeta(n, m).subtract(BigDecimal.ONE); c = multiplyRound(c, zetm1); if (n % 2 == 0) { resul = resul.add(c); } else { resul = resul.subtract(c); } /* alternating sum, so truncating as eps is reached suffices */ if (Math.abs(c.doubleValue()) < eps) { break; } } } /* The relative error in the result is the absolute error in the * input variable times the digamma (psi) value at that point. */ double psi = 0.5772156649; double zdbl = z.doubleValue(); for (int n = 1; n < 5; n++) { psi += zdbl / n / (n + zdbl); } eps = psi * x.ulp().doubleValue() / 2.; mcloc = new MathContext(err2prec(eps)); return exp(resul).round(mcloc); } }
From source file:org.zuinnote.hadoop.office.format.common.converter.ExcelConverterSimpleSpreadSheetCellDAO.java
/*** * This provides another sample to infer schema in form of simple datatypes * (e.g. boolean, byte etc.). You might add as many sample as necessary to get a * precise schema.//from ww w . j ava 2 s . c om * * @param dataRow */ public void updateSpreadSheetCellRowToInferSchemaInformation(SpreadSheetCellDAO[] dataRow) { // check size of cell based on address // if necessary add more to schemaRow for (SpreadSheetCellDAO currentSpreadSheetCellDAO : dataRow) { boolean dataTypeFound = false; if (currentSpreadSheetCellDAO != null) { // add potential column to list int j = new CellAddress(currentSpreadSheetCellDAO.getAddress()).getColumn(); if (j >= this.schemaRow.size()) { // fill up for (int x = this.schemaRow.size(); x <= j; x++) { this.schemaRow.add(null); } } // check if boolean data type if ((currentSpreadSheetCellDAO.getFormattedValue() != null) && (!"".equals(currentSpreadSheetCellDAO.getFormattedValue()))) { // skip null value String currentCellValue = currentSpreadSheetCellDAO.getFormattedValue(); // check if boolean if (("TRUE".equals(currentCellValue)) || ("FALSE".equals(currentCellValue))) { dataTypeFound = true; if (this.schemaRow.get(j) != null) { // check if previous assumption was boolean if (!(this.schemaRow.get(j) instanceof GenericBooleanDataType)) { // if not then the type needs to be set to string this.schemaRow.set(j, new GenericStringDataType()); } // if yes then nothing todo (already boolean) } else { // we face this the first time this.schemaRow.set(j, new GenericBooleanDataType()); } } // check if timestamp using provided format if (!dataTypeFound) { if (this.dateTimeFormat != null) { // only if a format is specified Date theDate = this.dateTimeFormat.parse(currentCellValue, new ParsePosition(0)); if (theDate != null) { // we found indeed a date time dataTypeFound = true; if (this.schemaRow.get(j) != null) { // check if previous assumption was date if (!(this.schemaRow.get(j) instanceof GenericTimestampDataType)) { // if not then the type needs to be set to string this.schemaRow.set(j, new GenericStringDataType()); } } else { // we face this the first time this.schemaRow.set(j, new GenericTimestampDataType()); } } } } // check for timestamp using java.sql.Timestamp if (!dataTypeFound) { try { java.sql.Timestamp ts = java.sql.Timestamp.valueOf(currentCellValue); dataTypeFound = true; this.schemaRow.set(j, new GenericTimestampDataType()); } catch (IllegalArgumentException e) { LOG.warn( "Could not identify timestamp using TimeStamp.valueOf. Trying last resort Date parsing...."); } } // check if date data type if (!dataTypeFound) { Date theDate = this.dateFormat.parse(currentCellValue, new ParsePosition(0)); if (theDate != null) { // we have indeed a date dataTypeFound = true; if (this.schemaRow.get(j) != null) { // check if previous assumption was date if (!(this.schemaRow.get(j) instanceof GenericDateDataType)) { // if not then the type needs to be set to string this.schemaRow.set(j, new GenericStringDataType()); } } else { // we face this the first time this.schemaRow.set(j, new GenericDateDataType()); // check if it has a time component } } } // check if BigDecimal BigDecimal bd = (BigDecimal) this.decimalFormat.parse(currentCellValue, new ParsePosition(0)); if ((!dataTypeFound) && (bd != null)) { BigDecimal bdv = bd.stripTrailingZeros(); dataTypeFound = true; if (this.schemaRow.get(j) != null) { // check if previous assumption was a number // check if we need to upgrade to decimal if ((bdv.scale() > 0) && (this.schemaRow.get(j) instanceof GenericNumericDataType)) { // upgrade to decimal, if necessary if (!(this.schemaRow.get(j) instanceof GenericBigDecimalDataType)) { this.schemaRow.set(j, new GenericBigDecimalDataType(bdv.precision(), bdv.scale())); } else { if ((bdv.scale() > ((GenericBigDecimalDataType) this.schemaRow.get(j)) .getScale()) && (bdv.precision() > ((GenericBigDecimalDataType) this.schemaRow .get(j)).getPrecision())) { this.schemaRow.set(j, new GenericBigDecimalDataType(bdv.precision(), bdv.scale())); } else if (bdv.scale() > ((GenericBigDecimalDataType) this.schemaRow.get(j)) .getScale()) { // upgrade scale GenericBigDecimalDataType gbd = ((GenericBigDecimalDataType) this.schemaRow .get(j)); gbd.setScale(bdv.scale()); this.schemaRow.set(j, gbd); } else if (bdv.precision() > ((GenericBigDecimalDataType) this.schemaRow.get(j)) .getPrecision()) { // upgrade precision // new precision is needed to extend to max scale GenericBigDecimalDataType gbd = ((GenericBigDecimalDataType) this.schemaRow .get(j)); int newpre = bdv.precision() + (gbd.getScale() - bdv.scale()); gbd.setPrecision(newpre); this.schemaRow.set(j, gbd); } } } else { // check if we need to upgrade one of the integer types // if current is byte boolean isByte = false; boolean isShort = false; boolean isInt = false; boolean isLong = true; try { bdv.longValueExact(); isLong = true; bdv.intValueExact(); isInt = true; bdv.shortValueExact(); isShort = true; bdv.byteValueExact(); isByte = true; } catch (Exception e) { LOG.debug("Possible data types: Long: " + isLong + " Int: " + isInt + " Short: " + isShort + " Byte: " + isByte); } // if it was Numeric before we can ignore testing the byte case, here just for // completeness if ((isByte) && ((this.schemaRow.get(j) instanceof GenericByteDataType) || (this.schemaRow.get(j) instanceof GenericShortDataType) || (this.schemaRow.get(j) instanceof GenericIntegerDataType) || (this.schemaRow.get(j) instanceof GenericLongDataType))) { // if it was Byte before we can ignore testing the byte case, here just for // completeness } else if ((isShort) && ((this.schemaRow.get(j) instanceof GenericByteDataType))) { // upgrade to short this.schemaRow.set(j, new GenericShortDataType()); } else if ((isInt) && ((this.schemaRow.get(j) instanceof GenericShortDataType) || (this.schemaRow.get(j) instanceof GenericByteDataType))) { // upgrade to integer this.schemaRow.set(j, new GenericIntegerDataType()); } else if ((!isByte) && (!isShort) && (!isInt) && !((this.schemaRow.get(j) instanceof GenericLongDataType))) { // upgrade to long this.schemaRow.set(j, new GenericLongDataType()); } } } else { // we face it for the first time // determine value type if (bdv.scale() > 0) { this.schemaRow.set(j, new GenericBigDecimalDataType(bdv.precision(), bdv.scale())); } else { boolean isByte = false; boolean isShort = false; boolean isInt = false; boolean isLong = true; try { bdv.longValueExact(); isLong = true; bdv.intValueExact(); isInt = true; bdv.shortValueExact(); isShort = true; bdv.byteValueExact(); isByte = true; } catch (Exception e) { LOG.debug("Possible data types: Long: " + isLong + " Int: " + isInt + " Short: " + isShort + " Byte: " + isByte); } if (isByte) { this.schemaRow.set(j, new GenericByteDataType()); } else if (isShort) { this.schemaRow.set(j, new GenericShortDataType()); } else if (isInt) { this.schemaRow.set(j, new GenericIntegerDataType()); } else if (isLong) { this.schemaRow.set(j, new GenericLongDataType()); } } } } if (!dataTypeFound) { // otherwise string if (!(this.schemaRow.get(j) instanceof GenericStringDataType)) { this.schemaRow.set(j, new GenericStringDataType()); } } } else { // ignore null values } } } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The exponential function./*from w w w .j a v a 2 s . c o m*/ * * @param x the argument. * @return exp(x). * The precision of the result is implicitly defined by the precision in the argument. * 16 * In particular this means that "Invalid Operation" errors are thrown if catastrophic * cancellation of digits causes the result to have no valid digits left. */ static public BigDecimal exp(BigDecimal x) { /* To calculate the value if x is negative, use exp(-x) = 1/exp(x) */ if (x.compareTo(BigDecimal.ZERO) < 0) { final BigDecimal invx = exp(x.negate()); /* Relative error in inverse of invx is the same as the relative errror in invx. * This is used to define the precision of the result. */ MathContext mc = new MathContext(invx.precision()); return BigDecimal.ONE.divide(invx, mc); } else if (x.compareTo(BigDecimal.ZERO) == 0) { /* recover the valid number of digits from x.ulp(), if x hits the * zero. The x.precision() is 1 then, and does not provide this information. */ return scalePrec(BigDecimal.ONE, -(int) (Math.log10(x.ulp().doubleValue()))); } else { /* Push the number in the Taylor expansion down to a small * value where TAYLOR_NTERM terms will do. If x<1, the n-th term is of the order * x^n/n!, and equal to both the absolute and relative error of the result * since the result is close to 1. The x.ulp() sets the relative and absolute error * of the result, as estimated from the first Taylor term. * We want x^TAYLOR_NTERM/TAYLOR_NTERM! < x.ulp, which is guaranteed if * x^TAYLOR_NTERM < TAYLOR_NTERM*(TAYLOR_NTERM-1)*...*x.ulp. */ final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue(); if (Math.pow(xDbl, TAYLOR_NTERM) < TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0) * xUlpDbl) { /* Add TAYLOR_NTERM terms of the Taylor expansion (Eulers sum formula) */ BigDecimal resul = BigDecimal.ONE; /* x^i */ BigDecimal xpowi = BigDecimal.ONE; /* i factorial */ BigInteger ifac = BigInteger.ONE; /* TAYLOR_NTERM terms to be added means we move x.ulp() to the right * for each power of 10 in TAYLOR_NTERM, so the addition wont add noise beyond * whats already in x. */ MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / TAYLOR_NTERM)); for (int i = 1; i <= TAYLOR_NTERM; i++) { ifac = ifac.multiply(new BigInteger("" + i)); xpowi = xpowi.multiply(x); final BigDecimal c = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(c); if (Math.abs(xpowi.doubleValue()) < i && Math.abs(c.doubleValue()) < 0.5 * xUlpDbl) { break; } } /* exp(x+deltax) = exp(x)(1+deltax) if deltax is <<1. So the relative error * in the result equals the absolute error in the argument. */ MathContext mc = new MathContext(err2prec(xUlpDbl / 2.)); return resul.round(mc); } else { /* Compute exp(x) = (exp(0.1*x))^10. Division by 10 does not lead * to loss of accuracy. */ int exSc = (int) (1.0 - Math.log10(TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0) * xUlpDbl / Math.pow(xDbl, TAYLOR_NTERM)) / (TAYLOR_NTERM - 1.0)); BigDecimal xby10 = x.scaleByPowerOfTen(-exSc); BigDecimal expxby10 = exp(xby10); /* Final powering by 10 means that the relative error of the result * is 10 times the relative error of the base (First order binomial expansion). * This looses one digit. */ MathContext mc = new MathContext(expxby10.precision() - exSc); /* Rescaling the powers of 10 is done in chunks of a maximum of 8 to avoid an invalid operation 17 * response by the BigDecimal.pow library or integer overflow. */ while (exSc > 0) { int exsub = Math.min(8, exSc); exSc -= exsub; MathContext mctmp = new MathContext(expxby10.precision() - exsub + 2); int pex = 1; while (exsub-- > 0) { pex *= 10; } expxby10 = expxby10.pow(pex, mctmp); } return expxby10.round(mc); } } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The natural logarithm.//from ww w .ja v a 2 s.c o m * * @param x the argument. * @return ln(x). * The precision of the result is implicitly defined by the precision in the argument. */ static public BigDecimal log(BigDecimal x) { /* the value is undefined if x is negative. */ if (x.compareTo(BigDecimal.ZERO) < 0) { throw new ArithmeticException("Cannot take log of negative " + x.toString()); } else if (x.compareTo(BigDecimal.ONE) == 0) { /* log 1. = 0. */ return scalePrec(BigDecimal.ZERO, x.precision() - 1); } else if (Math.abs(x.doubleValue() - 1.0) <= 0.3) { /* The standard Taylor series around x=1, z=0, z=x-1. Abramowitz-Stegun 4.124. * The absolute error is err(z)/(1+z) = err(x)/x. */ BigDecimal z = scalePrec(x.subtract(BigDecimal.ONE), 2); BigDecimal zpown = z; double eps = 0.5 * x.ulp().doubleValue() / Math.abs(x.doubleValue()); BigDecimal resul = z; for (int k = 2;; k++) { zpown = multiplyRound(zpown, z); BigDecimal c = divideRound(zpown, k); if (k % 2 == 0) { resul = resul.subtract(c); } else { resul = resul.add(c); } if (Math.abs(c.doubleValue()) < eps) { break; } } MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps)); return resul.round(mc); } else { final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue(); /* Map log(x) = log root[r](x)^r = r*log( root[r](x)) with the aim * to move roor[r](x) near to 1.2 (that is, below the 0.3 appearing above), where log(1.2) is roughly 0.2. */ int r = (int) (Math.log(xDbl) / 0.2); /* Since the actual requirement is a function of the value 0.3 appearing above, * we avoid the hypothetical case of endless recurrence by ensuring that r >= 2. */ r = Math.max(2, r); /* Compute r-th root with 2 additional digits of precision */ BigDecimal xhighpr = scalePrec(x, 2); BigDecimal resul = root(r, xhighpr); resul = log(resul).multiply(new BigDecimal(r)); /* error propagation: log(x+errx) = log(x)+errx/x, so the absolute error * in the result equals the relative error in the input, xUlpDbl/xDbl . */ MathContext mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl / xDbl)); return resul.round(mc); } }
From source file:com.qcadoo.mes.productionScheduling.listeners.OrderTimePredictionListeners.java
@Transactional public void changeRealizationTime(final ViewDefinitionState view, final ComponentState state, final String[] args) { FormComponent orderForm = (FormComponent) view.getComponentByReference(L_FORM); FieldComponent technologyLookup = (FieldComponent) view.getComponentByReference(OrderFields.TECHNOLOGY); FieldComponent plannedQuantityField = (FieldComponent) view .getComponentByReference(OrderFields.PLANNED_QUANTITY); FieldComponent dateFromField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_FROM); FieldComponent dateToField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_TO); FieldComponent productionLineLookup = (FieldComponent) view .getComponentByReference(OrderFields.PRODUCTION_LINE); boolean isGenerated = false; if (technologyLookup.getFieldValue() == null) { technologyLookup.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE); return;/*w w w.j a v a2 s. co m*/ } if (!StringUtils.hasText((String) dateFromField.getFieldValue())) { dateFromField.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE); return; } if (!StringUtils.hasText((String) plannedQuantityField.getFieldValue())) { plannedQuantityField.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE); return; } if (productionLineLookup.getFieldValue() == null) { productionLineLookup.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE); return; } BigDecimal quantity = null; Object value = plannedQuantityField.getFieldValue(); if (value instanceof BigDecimal) { quantity = (BigDecimal) value; } else { try { ParsePosition parsePosition = new ParsePosition(0); String trimedValue = value.toString().replaceAll(" ", ""); DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(view.getLocale()); formatter.setParseBigDecimal(true); quantity = new BigDecimal(String.valueOf(formatter.parseObject(trimedValue, parsePosition))); } catch (NumberFormatException e) { plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidNumericFormat", MessageType.FAILURE); return; } } int scale = quantity.scale(); if (MAX != null && scale > MAX) { plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidScale.max", MessageType.FAILURE, MAX.toString()); return; } int presicion = quantity.precision() - scale; if (MAX != null && presicion > MAX) { plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidPrecision.max", MessageType.FAILURE, MAX.toString()); return; } if (BigDecimal.ZERO.compareTo(quantity) >= 0) { plannedQuantityField.addMessage("qcadooView.validate.field.error.outOfRange.toSmall", MessageType.FAILURE); return; } int maxPathTime = 0; Entity technology = dataDefinitionService .get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY) .get((Long) technologyLookup.getFieldValue()); Validate.notNull(technology, "technology is null"); if (technology.getStringField(TechnologyFields.STATE).equals(TechnologyState.DRAFT.getStringValue()) || technology.getStringField(TechnologyFields.STATE) .equals(TechnologyState.OUTDATED.getStringValue())) { technologyLookup.addMessage("productionScheduling.technology.incorrectState", MessageType.FAILURE); return; } FieldComponent laborWorkTimeField = (FieldComponent) view .getComponentByReference(OrderFieldsPS.LABOR_WORK_TIME); FieldComponent machineWorkTimeField = (FieldComponent) view .getComponentByReference(OrderFieldsPS.MACHINE_WORK_TIME); FieldComponent includeTpzField = (FieldComponent) view.getComponentByReference(OrderFieldsPS.INCLUDE_TPZ); FieldComponent includeAdditionalTimeField = (FieldComponent) view .getComponentByReference(OrderFieldsPS.INCLUDE_ADDITIONAL_TIME); Boolean includeTpz = "1".equals(includeTpzField.getFieldValue()); Boolean includeAdditionalTime = "1".equals(includeAdditionalTimeField.getFieldValue()); Entity productionLine = dataDefinitionService .get(ProductionLinesConstants.PLUGIN_IDENTIFIER, ProductionLinesConstants.MODEL_PRODUCTION_LINE) .get((Long) productionLineLookup.getFieldValue()); final Map<Long, BigDecimal> operationRuns = Maps.newHashMap(); productQuantitiesService.getProductComponentQuantities(technology, quantity, operationRuns); OperationWorkTime workTime = operationWorkTimeService.estimateTotalWorkTimeForTechnology(technology, operationRuns, includeTpz, includeAdditionalTime, productionLine, true); laborWorkTimeField.setFieldValue(workTime.getLaborWorkTime()); machineWorkTimeField.setFieldValue(workTime.getMachineWorkTime()); maxPathTime = orderRealizationTimeService.estimateOperationTimeConsumption( technology.getTreeField(TechnologyFields.OPERATION_COMPONENTS).getRoot(), quantity, includeTpz, includeAdditionalTime, productionLine); if (maxPathTime > OrderRealizationTimeService.MAX_REALIZATION_TIME) { state.addMessage("orders.validate.global.error.RealizationTimeIsToLong", MessageType.FAILURE); dateToField.setFieldValue(null); } else { Date startTime = DateUtils.parseDate(dateFromField.getFieldValue()); if (startTime == null) { dateFromField.addMessage("orders.validate.global.error.dateFromIsNull", MessageType.FAILURE); } else { Date stopTime = shiftsService.findDateToForOrder(startTime, maxPathTime); if (stopTime == null) { orderForm.addMessage("productionScheduling.timenorms.isZero", MessageType.FAILURE, false); dateToField.setFieldValue(null); } else { dateToField.setFieldValue(orderRealizationTimeService.setDateToField(stopTime)); startTime = shiftsService.findDateFromForOrder(stopTime, maxPathTime); scheduleOperationComponents(technology.getId(), startTime); isGenerated = true; } if (startTime != null) { orderForm.addMessage("orders.dateFrom.info.dateFromSetToFirstPossible", MessageType.INFO, false); } } } laborWorkTimeField.requestComponentUpdateState(); machineWorkTimeField.requestComponentUpdateState(); dateFromField.requestComponentUpdateState(); dateToField.requestComponentUpdateState(); orderForm.setEntity(orderForm.getEntity()); state.performEvent(view, "refresh", new String[0]); if (isGenerated) { orderForm.addMessage("productionScheduling.info.calculationGenerated", MessageType.SUCCESS); } }
From source file:com.aimluck.eip.project.ProjectTaskFormData.java
/** * ????//from w w w. j a v a2 s . c o m * * @param rundata * RunData * @param context * Context * @param msgList * * @return TRUE ? FALSE */ @Override protected boolean setFormData(RunData rundata, Context context, List<String> msgList) throws ALPageNotFoundException, ALDBErrorException { boolean res = super.setFormData(rundata, context, msgList); try { if (res) { String members[] = rundata.getParameters().getStrings("task_member"); String workload[] = rundata.getParameters().getStrings("workload"); if (members != null) { for (int i = 0; i < members.length; i++) { if (members[i] == null || members[i].length() == 0) { continue; } // ALEipUser user = ALEipUtils.getALEipUser(Integer.valueOf(members[i])); // BigDecimal w = BigDecimal.valueOf(0); try { if (workload[i] != null && workload[i].length() > 0) { w = new BigDecimal(workload[i]); } if (w.compareTo(BigDecimal.valueOf(0)) < 0) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD")); } else if (w.precision() - w.scale() > 5) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD_RATIONAL_INTEGER")); } else if (w.scale() > 3) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD_DECIMAL")); } } catch (Exception e) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD_INTEGER")); } ProjectTaskMemberResultData member = new ProjectTaskMemberResultData(); member.initField(); member.setUserId(user.getUserId().getValue()); member.setUserName(user.getAliasName().getValue()); member.setWorkload(w); taskMembers.add(member); } } planWorkloadString = rundata.getParameters().getString("plan_workload"); // fileuploadList = pfile.getFileuploadList(rundata); if (ALEipConstants.MODE_NEW_FORM.equals(getMode())) { String nullStr = null; start_date_check.setValue("TRUE"); start_date.setValue(nullStr); end_date_check.setValue("TRUE"); end_date.setValue(nullStr); } } } catch (RuntimeException ex) { logger.error("RuntimeException", ex); res = false; } catch (Exception ex) { logger.error("Exception", ex); res = false; } return res; }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Trigonometric cosine./*from w w w .ja v a2 s. c o m*/ * * @param x The argument in radians. * @return cos(x) in the range -1 to 1. */ static public BigDecimal cos(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return cos(x.negate()); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ONE; } else { /* reduce modulo 2pi */ BigDecimal res = mod2pi(x); double errpi = 0.5 * Math.abs(x.ulp().doubleValue()); int val = +err2prec(FastMath.PI, errpi); MathContext mc = new MathContext(val); BigDecimal p = pi(mc); mc = new MathContext(x.precision()); if (res.compareTo(p) > 0) { /* pi<x<=2pi: cos(x)= - cos(x-pi) */ return cos(subtractRound(res, p)).negate(); } else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) { /* pi/2<x<=pi: cos(x)= -cos(pi-x) */ return cos(subtractRound(p, res)).negate(); } else { /* for the range 0<=x<Pi/2 one could use cos(2x)= 1-2*sin^2(x) * to split this further, or use the cos up to pi/4 and the sine higher up. throw new ProviderException("Unimplemented cosine ") ; */ if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) { /* x>pi/4: cos(x) = sin(pi/2-x) */ return sin(subtractRound(p.divide(new BigDecimal("2")), res)); } else { /* Simple Taylor expansion, sum_{i=0..infinity} (-1)^(..)res^(2i)/(2i)! */ BigDecimal resul = BigDecimal.ONE; /* x^i */ BigDecimal xpowi = BigDecimal.ONE; /* 2i factorial */ BigInteger ifac = BigInteger.ONE; /* The absolute error in the result is the error in x^2/2 which is x times the error in x. */ double xUlpDbl = 0.5 * res.ulp().doubleValue() * res.doubleValue(); /* The error in the result is set by the error in x^2/2 itself, xUlpDbl. * We need at most k terms to push x^(2k+1)/(2k+1)! below this value. * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); */ int k = (int) (Math.log(xUlpDbl) / Math.log(res.doubleValue())) / 2; MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i-1 or 2*i overflow? */ ifac = ifac.multiply(new BigInteger("" + (2 * i - 1))); ifac = ifac.multiply(new BigInteger("" + (2 * i))); xpowi = xpowi.multiply(res).multiply(res).negate(); BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(corr); if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { break; } } /* The error in the result is governed by the error in x itself. */ mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl)); return resul.round(mc); } } } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Trigonometric sine.//w w w . j av a 2s. c o m * * @param x The argument in radians. * @return sin(x) in the range -1 to 1. */ static public BigDecimal sin(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return sin(x.negate()).negate(); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { /* reduce modulo 2pi */ BigDecimal res = mod2pi(x); double errpi = 0.5 * Math.abs(x.ulp().doubleValue()); int val = 2 + err2prec(FastMath.PI, errpi); MathContext mc = new MathContext(val); BigDecimal p = pi(mc); mc = new MathContext(x.precision()); if (res.compareTo(p) > 0) { /* pi<x<=2pi: sin(x)= - sin(x-pi) */ return sin(subtractRound(res, p)).negate(); } else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) { /* pi/2<x<=pi: sin(x)= sin(pi-x) */ return sin(subtractRound(p, res)); } else { /* for the range 0<=x<Pi/2 one could use sin(2x)=2sin(x)cos(x) * to split this further. Here, use the sine up to pi/4 and the cosine higher up. */ if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) { /* x>pi/4: sin(x) = cos(pi/2-x) */ return cos(subtractRound(p.divide(new BigDecimal("2")), res)); } else { /* Simple Taylor expansion, sum_{i=1..infinity} (-1)^(..)res^(2i+1)/(2i+1)! */ BigDecimal resul = res; /* x^i */ BigDecimal xpowi = res; /* 2i+1 factorial */ BigInteger ifac = BigInteger.ONE; /* The error in the result is set by the error in x itself. */ double xUlpDbl = res.ulp().doubleValue(); /* The error in the result is set by the error in x itself. * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value. * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision; * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision */ int k = (int) (res.precision() / Math.log10(1.0 / res.doubleValue())) / 2; MathContext mcTay = new MathContext(err2prec(res.doubleValue(), xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i or 2*i+1 overflow? */ ifac = ifac.multiply(new BigInteger("" + (2 * i))); ifac = ifac.multiply(new BigInteger("" + (2 * i + 1))); xpowi = xpowi.multiply(res).multiply(res).negate(); BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(corr); if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { break; } } /* The error in the result is set by the error in x itself. */ mc = new MathContext(res.precision()); return resul.round(mc); } } } /* sin */ }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The integer root.//from w w w .j a va2s .c om * * @param n the positive argument. * @param x the non-negative argument. * @return The n-th root of the BigDecimal rounded to the precision implied by x, x^(1/n). */ static public BigDecimal root(final int n, final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { throw new ArithmeticException("negative argument " + x.toString() + " of root"); } if (n <= 0) { throw new ArithmeticException("negative power " + n + " of root"); } if (n == 1) { return x; } /* start the computation from a double precision estimate */ BigDecimal s = new BigDecimal(Math.pow(x.doubleValue(), 1.0 / n)); /* this creates nth with nominal precision of 1 digit */ final BigDecimal nth = new BigDecimal(n); /* Specify an internal accuracy within the loop which is * slightly larger than what is demanded by eps below. */ final BigDecimal xhighpr = scalePrec(x, 2); MathContext mc = new MathContext(2 + x.precision()); /* Relative accuracy of the result is eps. */ final double eps = x.ulp().doubleValue() / (2 * n * x.doubleValue()); for (;;) { /* s = s -(s/n-x/n/s^(n-1)) = s-(s-x/s^(n-1))/n; test correction s/n-x/s for being * smaller than the precision requested. The relative correction is (1-x/s^n)/n, */ BigDecimal c = xhighpr.divide(s.pow(n - 1), mc); c = s.subtract(c); MathContext locmc = new MathContext(c.precision()); c = c.divide(nth, locmc); s = s.subtract(c); if (Math.abs(c.doubleValue() / s.doubleValue()) < eps) { break; } } return s.round(new MathContext(err2prec(eps))); }
From source file:com.healthmarketscience.jackcess.impl.ColumnImpl.java
/** * Writes a numeric value.// w w w. j a v a 2 s.c o m */ private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException { Object inValue = value; try { BigDecimal decVal = toBigDecimal(value); inValue = decVal; int signum = decVal.signum(); if (signum < 0) { decVal = decVal.negate(); } // write sign byte buffer.put((signum < 0) ? NUMERIC_NEGATIVE_BYTE : 0); // adjust scale according to this column type (will cause the an // ArithmeticException if number has too many decimal places) decVal = decVal.setScale(getScale()); // check precision if (decVal.precision() > getPrecision()) { throw new IOException( "Numeric value is too big for specified precision " + getPrecision() + ": " + decVal); } // convert to unscaled BigInteger, big-endian bytes byte[] intValBytes = toUnscaledByteArray(decVal, getType().getFixedSize() - 1); if (buffer.order() != ByteOrder.BIG_ENDIAN) { fixNumericByteOrder(intValBytes); } buffer.put(intValBytes); } catch (ArithmeticException e) { throw (IOException) new IOException("Numeric value '" + inValue + "' out of range").initCause(e); } }