Example usage for java.math BigDecimal precision

List of usage examples for java.math BigDecimal precision

Introduction

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

Prototype

int precision

To view the source code for java.math BigDecimal precision.

Click Source Link

Document

The number of decimal digits in this BigDecimal, or 0 if the number of digits are not known (lookaside information).

Usage

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The inverse trigonometric sine./*from  w w  w . ja va 2  s  .c o 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:net.groupbuy.controller.shop.PaymentController.java

/**
 * ??/*w w  w  .  j a  v a 2 s  .  c  om*/
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submit(Type type, String paymentPluginId, String sn, BigDecimal amount,
        HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    Member member = memberService.getCurrent();
    if (member == null) {
        return ERROR_VIEW;
    }
    PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
    if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
        return ERROR_VIEW;
    }
    Payment payment = new Payment();
    String description = null;
    if (type == Type.payment) {
        Order order = orderService.findBySn(sn);
        if (order == null || !member.equals(order.getMember()) || order.isExpired() || order.isLocked(null)) {
            return ERROR_VIEW;
        }
        if (order.getPaymentMethod() == null
                || order.getPaymentMethod().getMethod() != PaymentMethod.Method.online) {
            return ERROR_VIEW;
        }
        if (order.getPaymentStatus() != PaymentStatus.unpaid
                && order.getPaymentStatus() != PaymentStatus.partialPayment) {
            return ERROR_VIEW;
        }
        if (order.getAmountPayable().compareTo(new BigDecimal(0)) <= 0) {
            return ERROR_VIEW;
        }
        payment.setSn(snService.generate(Sn.Type.payment));
        payment.setType(Type.payment);
        payment.setMethod(Method.online);
        payment.setStatus(Status.wait);
        payment.setPaymentMethod(order.getPaymentMethodName() + Payment.PAYMENT_METHOD_SEPARATOR
                + paymentPlugin.getPaymentName());
        payment.setFee(paymentPlugin.calculateFee(order.getAmountPayable()));
        payment.setAmount(paymentPlugin.calculateAmount(order.getAmountPayable()));
        payment.setPaymentPluginId(paymentPluginId);
        payment.setExpire(paymentPlugin.getTimeout() != null
                ? DateUtils.addMinutes(new Date(), paymentPlugin.getTimeout())
                : null);
        payment.setOrder(order);
        paymentService.save(payment);
        description = order.getName();
    } else if (type == Type.recharge) {
        Setting setting = SettingUtils.get();
        if (amount == null || amount.compareTo(new BigDecimal(0)) <= 0 || amount.precision() > 15
                || amount.scale() > setting.getPriceScale()) {
            return ERROR_VIEW;
        }
        payment.setSn(snService.generate(Sn.Type.payment));
        payment.setType(Type.recharge);
        payment.setMethod(Method.online);
        payment.setStatus(Status.wait);
        payment.setPaymentMethod(paymentPlugin.getPaymentName());
        payment.setFee(paymentPlugin.calculateFee(amount));
        payment.setAmount(paymentPlugin.calculateAmount(amount));
        payment.setPaymentPluginId(paymentPluginId);
        payment.setExpire(paymentPlugin.getTimeout() != null
                ? DateUtils.addMinutes(new Date(), paymentPlugin.getTimeout())
                : null);
        payment.setMember(member);
        paymentService.save(payment);
        description = message("shop.member.deposit.recharge");
    } else {
        return ERROR_VIEW;
    }
    model.addAttribute("requestUrl", paymentPlugin.getRequestUrl());
    model.addAttribute("requestMethod", paymentPlugin.getRequestMethod());
    model.addAttribute("requestCharset", paymentPlugin.getRequestCharset());
    model.addAttribute("parameterMap", paymentPlugin.getParameterMap(payment.getSn(), description, request));
    if (StringUtils.isNotEmpty(paymentPlugin.getRequestCharset())) {
        response.setContentType("text/html; charset=" + paymentPlugin.getRequestCharset());
    }
    return "shop/payment/submit";
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * Writes a numeric value.//from   ww  w .  j  a va 2  s  .c  o m
 */
private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException {
    Object inValue = value;
    try {
        BigDecimal decVal = toBigDecimal(value);
        inValue = decVal;

        boolean negative = (decVal.compareTo(BigDecimal.ZERO) < 0);
        if (negative) {
            decVal = decVal.negate();
        }

        // write sign byte
        buffer.put(negative ? (byte) 0x80 : (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 = decVal.unscaledValue().toByteArray();
        int maxByteLen = getType().getFixedSize() - 1;
        if (intValBytes.length > maxByteLen) {
            throw new IOException("Too many bytes for valid BigInteger?");
        }
        if (intValBytes.length < maxByteLen) {
            byte[] tmpBytes = new byte[maxByteLen];
            System.arraycopy(intValBytes, 0, tmpBytes, (maxByteLen - intValBytes.length), intValBytes.length);
            intValBytes = tmpBytes;
        }
        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);
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hyperbolic sine./*from ww  w  . j a va  2 s .co  m*/
 *
 * @param x the argument.
 * @return the sinh(x) = (exp(x)-exp(-x))/2 .
 */
static public BigDecimal sinh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return sinh(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        if (x.doubleValue() > 2.4) {
            /* Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x).
             */
            BigDecimal two = new BigDecimal(2);
            BigDecimal xhalf = x.divide(two);

            BigDecimal resul = sinh(xhalf).multiply(cosh(xhalf)).multiply(two);
            /* The error in the result is set by the error in x itself.
             * The first derivative of sinh(x) is cosh(x), so the absolute error
             * in the result is cosh(x)*errx, and the relative error is coth(x)*errx = errx/tanh(x)
             */

            double eps = Math.tanh(x.doubleValue());
            MathContext mc = new MathContext(err2prec(0.5 * x.ulp().doubleValue() / eps));

            return resul.round(mc);

        } else {
            BigDecimal xhighpr = scalePrec(x, 2);
            /* Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! */
            BigDecimal resul = xhighpr;
            /* x^i */
            BigDecimal xpowi = xhighpr;
            /* 2i+1 factorial */
            BigInteger ifac = BigInteger.ONE;
            /* The error in the result is set by the error in x itself.
             */

            double xUlpDbl = x.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) (x.precision() / Math.log10(1.0 / xhighpr.doubleValue())) / 2;
            MathContext mcTay = new MathContext(err2prec(x.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(xhighpr).multiply(xhighpr);
                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.
              */
            MathContext mc = new MathContext(x.precision());

            return resul.round(mc);

        }
    }
}

From source file:ca.oson.json.Oson.java

private <E, R> String bigDecimal2Json(FieldData objectDTO) {
    if (objectDTO == null || objectDTO.json2Java) {
        return null;
    }/* w  ww  . j a  v  a 2  s .c  om*/

    E value = (E) objectDTO.valueToProcess;
    Class<R> returnType = objectDTO.returnType;

    if (value != null && value.toString().trim().length() > 0) {
        BigDecimal valueToProcess = null;
        String valueToReturn = null;

        if (value instanceof BigDecimal) {
            valueToProcess = (BigDecimal) value;
        } else {
            try {
                valueToProcess = new BigDecimal(value.toString().trim());
            } catch (Exception ex) {
            }
        }

        if (valueToProcess != null) {
            try {
                Function function = objectDTO.getSerializer();
                if (function != null) {
                    try {
                        if (function instanceof DataMapper2JsonFunction) {
                            DataMapper classData = new DataMapper(returnType, value, objectDTO.classMapper,
                                    objectDTO.level, getPrettyIndentation());
                            return ((DataMapper2JsonFunction) function).apply(classData);

                        } else if (function instanceof BigDecimal2JsonFunction) {
                            return ((BigDecimal2JsonFunction) function).apply(valueToProcess);

                        } else {

                            Object returnedValue = null;
                            if (function instanceof FieldData2JsonFunction) {
                                FieldData2JsonFunction f = (FieldData2JsonFunction) function;
                                FieldData fieldData = objectDTO.clone();
                                returnedValue = f.apply(fieldData);
                            } else {
                                returnedValue = function.apply(value);
                            }

                            if (returnedValue instanceof Optional) {
                                returnedValue = ObjectUtil.unwrap(returnedValue);
                            }

                            if (returnedValue == null) {
                                return null;

                            } else if (returnedValue instanceof BigDecimal) {
                                valueToProcess = (BigDecimal) returnedValue;

                            } else {
                                objectDTO.valueToProcess = returnedValue;
                                return object2String(objectDTO);
                            }

                        }

                    } catch (Exception e) {
                    }
                }

                if (valueToProcess != null) {
                    Long min = objectDTO.getMin();
                    Long max = objectDTO.getMax();

                    if (min != null && valueToProcess.compareTo(new BigDecimal(min)) < 0) {
                        valueToProcess = new BigDecimal(min);
                    }

                    if (max != null && valueToProcess.compareTo(new BigDecimal(max)) > 0) {
                        valueToProcess = new BigDecimal(max);
                    }

                    Integer precision = objectDTO.getPrecision();
                    Integer scale = objectDTO.getScale();

                    if (precision != null && precision < valueToProcess.precision()) {
                        valueToProcess = (BigDecimal) NumberUtil.setPrecision(valueToProcess, precision,
                                getRoundingMode());

                        if (scale != null) {
                            valueToProcess = valueToProcess.setScale(scale, getRoundingMode());
                        }

                    } else if (scale != null) {
                        valueToProcess = valueToProcess.setScale(scale, getRoundingMode());
                    }

                    return NumberUtil.appendingFloatingZero(NumberUtil.toPlainString(valueToProcess),
                            this.isAppendingFloatingZero());
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    return bigDecimal2JsonDefault(objectDTO);
}

From source file:ca.oson.json.Oson.java

private <E, R> BigDecimal json2BigDecimal(FieldData objectDTO) {
    if (objectDTO == null || !objectDTO.json2Java) {
        return null;
    }/*from   w w w.  j  a va 2 s. c om*/

    E value = (E) objectDTO.valueToProcess;
    Class<R> returnType = objectDTO.returnType;

    if (value != null && value.toString().trim().length() > 0) {
        String valueToProcess = value.toString().trim();
        BigDecimal valueToReturn = null;

        try {
            Function function = objectDTO.getDeserializer();

            if (function != null) {
                try {
                    Object returnedValue = null;

                    if (function instanceof Json2DataMapperFunction) {
                        DataMapper classData = new DataMapper(returnType, value, objectDTO.classMapper,
                                objectDTO.level, getPrettyIndentation());
                        returnedValue = ((Json2DataMapperFunction) function).apply(classData);

                    } else if (function instanceof Json2FieldDataFunction) {
                        Json2FieldDataFunction f = (Json2FieldDataFunction) function;
                        FieldData fieldData = objectDTO.clone();

                        returnedValue = f.apply(fieldData);

                    } else if (function instanceof Json2BigDecimalFunction) {
                        return ((Json2BigDecimalFunction) function).apply(valueToProcess);
                    } else {
                        returnedValue = function.apply(valueToProcess);
                    }

                    if (returnedValue instanceof Optional) {
                        returnedValue = ObjectUtil.unwrap(returnedValue);
                    }

                    if (returnedValue == null) {
                        return null;

                    } else if (Number.class.isAssignableFrom(returnedValue.getClass())
                            || returnedValue.getClass().isPrimitive()) {

                        if (returnedValue instanceof BigDecimal) {
                            valueToReturn = (BigDecimal) returnedValue;
                        } else if (returnedValue instanceof String) {
                            valueToReturn = new BigDecimal((String) returnedValue);

                        } else if (returnedValue instanceof Integer) {
                            valueToReturn = new BigDecimal((Integer) returnedValue);
                        } else if (returnedValue instanceof Long) {
                            valueToReturn = new BigDecimal((Long) returnedValue);
                        } else if (returnedValue instanceof Short) {
                            valueToReturn = new BigDecimal((Short) returnedValue);
                        } else if (returnedValue instanceof Double) {
                            valueToReturn = new BigDecimal((Double) returnedValue);
                        } else if (returnedValue instanceof Float) {
                            valueToReturn = new BigDecimal((Float) returnedValue);
                        } else if (returnedValue instanceof BigInteger) {
                            valueToReturn = new BigDecimal((BigInteger) returnedValue);
                        } else if (returnedValue instanceof Byte) {
                            valueToReturn = new BigDecimal((Byte) returnedValue);
                        } else if (returnedValue instanceof AtomicInteger) {
                            valueToReturn = new BigDecimal(((AtomicInteger) returnedValue).intValue());
                        } else if (returnedValue instanceof AtomicLong) {
                            valueToReturn = new BigDecimal(((AtomicLong) returnedValue).longValue());
                        } else {
                            valueToReturn = new BigDecimal(((Number) returnedValue).doubleValue());
                        }

                    } else if (returnedValue instanceof Character) {
                        char c = (Character) returnedValue;
                        valueToReturn = new BigDecimal(Character.getNumericValue((Character) returnedValue));

                    } else if (returnedValue instanceof Boolean) {
                        if ((Boolean) returnedValue)
                            valueToReturn = new BigDecimal(1);
                        else
                            valueToReturn = new BigDecimal(0);

                    } else if (Enum.class.isAssignableFrom(returnedValue.getClass())) {
                        valueToReturn = new BigDecimal((Integer) ((Enum) returnedValue).ordinal());

                    } else if (Date.class.isAssignableFrom(returnedValue.getClass())) {
                        valueToReturn = new BigDecimal(((Date) returnedValue).getTime());

                    } else {
                        valueToReturn = new BigDecimal((returnedValue.toString()));
                    }

                    return valueToReturn;

                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                valueToReturn = new BigDecimal(valueToProcess);
            }

            if (valueToReturn != null) {
                Long min = objectDTO.getMin();
                Long max = objectDTO.getMax();

                if (min != null && valueToReturn.compareTo(new BigDecimal(min)) < 0) {
                    return new BigDecimal(min);
                }

                if (max != null && valueToReturn.compareTo(new BigDecimal(max)) > 0) {
                    valueToReturn = new BigDecimal(max);
                }

                Integer precision = objectDTO.getPrecision();
                if (precision != null && precision < valueToReturn.precision()) {
                    valueToReturn = (BigDecimal) NumberUtil.setPrecision(valueToReturn, precision,
                            getRoundingMode());
                }

                Integer scale = objectDTO.getScale();
                if (scale != null) {
                    valueToReturn = valueToReturn.setScale(scale, getRoundingMode());
                }

                return valueToReturn;
            }

        } catch (Exception ex) {
            //ex.printStackTrace();
        }

    }

    return json2BigDecimalDefault(objectDTO);
}