Example usage for java.math BigDecimal ONE

List of usage examples for java.math BigDecimal ONE

Introduction

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

Prototype

BigDecimal ONE

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

Click Source Link

Document

The value 1, with a scale of 0.

Usage

From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POCast.java

@SuppressWarnings({ "unchecked", "deprecation" })
private Object convertWithSchema(Object obj, ResourceFieldSchema fs) throws IOException {
    Object result = null;/*from ww w . j av a 2  s  .c  om*/

    if (fs == null) {
        return obj;
    }

    if (obj == null) {
        // handle DataType.NULL
        return null;
    }

    switch (fs.getType()) {
    case DataType.BAG:
        if (obj instanceof DataBag) {
            DataBag db = (DataBag) obj;
            // Get inner schema of a bag
            if (fs.getSchema() != null) {
                ResourceFieldSchema tupleFs = fs.getSchema().getFields()[0];
                Iterator<Tuple> iter = db.iterator();

                while (iter.hasNext()) {
                    Tuple t = iter.next();
                    convertWithSchema(t, tupleFs);
                }
            }
            result = db;
        } else if (obj instanceof DataByteArray) {
            if (null != caster) {
                result = caster.bytesToBag(((DataByteArray) obj).get(), fs);
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "bag.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
        } else {
            throw new ExecException("Cannot cast " + obj + " to bag.", 1120, PigException.INPUT);
        }
        break;
    case DataType.TUPLE:
        if (obj instanceof Tuple) {
            try {
                Tuple t = (Tuple) obj;
                ResourceSchema innerSchema = fs.getSchema();
                if (innerSchema == null)
                    return t;
                if (innerSchema.getFields().length != t.size())
                    return null;
                int i = 0;
                for (ResourceFieldSchema fieldSchema : innerSchema.getFields()) {
                    Object field = convertWithSchema(t.get(i), fieldSchema);
                    t.set(i, field);
                    i++;
                }
                result = t;
            } catch (Exception e) {
                throw new ExecException("Cannot convert " + obj + " to " + fs);
            }
        } else if (obj instanceof DataByteArray) {
            if (null != caster) {
                result = caster.bytesToTuple(((DataByteArray) obj).get(), fs);
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "tuple.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
        } else {
            throw new ExecException("Cannot cast " + obj + " to tuple.", 1120, PigException.INPUT);
        }
        break;
    case DataType.MAP:
        if (obj instanceof Map) {
            if (fs != null && fs.getSchema() != null) {
                ResourceFieldSchema innerFieldSchema = fs.getSchema().getFields()[0];
                Map m = (Map) obj;
                for (Object entry : m.entrySet()) {
                    Object newValue = convertWithSchema(((Map.Entry) entry).getValue(), innerFieldSchema);
                    m.put(((Map.Entry) entry).getKey(), newValue);
                }
                result = m;
            } else
                result = obj;
        } else if (obj instanceof DataByteArray) {
            if (null != caster) {
                result = caster.bytesToMap(((DataByteArray) obj).get(), fs);
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "tuple.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
        } else {
            throw new ExecException("Cannot cast " + obj + " to map.", 1120, PigException.INPUT);
        }
        break;
    case DataType.BOOLEAN:
        switch (DataType.findType(obj)) {
        case DataType.BYTEARRAY:
            if (null != caster) {
                result = caster.bytesToBoolean(((DataByteArray) obj).get());
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "int.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
            break;
        case DataType.BOOLEAN:
            result = obj;
            break;
        case DataType.INTEGER:
            result = Boolean.valueOf(((Integer) obj).intValue() != 0);
            ;
            break;
        case DataType.DOUBLE:
            result = Boolean.valueOf(((Double) obj).doubleValue() != 0.0D);
            break;
        case DataType.LONG:
            result = Boolean.valueOf(((Long) obj).longValue() != 0L);
            break;
        case DataType.FLOAT:
            result = Boolean.valueOf(((Float) obj).floatValue() != 0.0F);
            break;
        case DataType.CHARARRAY:
            result = CastUtils.stringToBoolean((String) obj);
            break;
        case DataType.BIGINTEGER:
            result = Boolean.valueOf(!BigInteger.ZERO.equals((BigInteger) obj));
            break;
        case DataType.BIGDECIMAL:
            result = Boolean.valueOf(!BigDecimal.ZERO.equals((BigDecimal) obj));
            break;
        default:
            throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT);
        }
        break;
    case DataType.INTEGER:
        switch (DataType.findType(obj)) {
        case DataType.BYTEARRAY:
            if (null != caster) {
                result = caster.bytesToInteger(((DataByteArray) obj).get());
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "int.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
            break;
        case DataType.BOOLEAN:
            if ((Boolean) obj) {
                result = Integer.valueOf(1);
            } else {
                result = Integer.valueOf(0);
            }
            break;
        case DataType.INTEGER:
            result = obj;
            break;
        case DataType.DOUBLE:
            result = Integer.valueOf(((Double) obj).intValue());
            break;
        case DataType.LONG:
            result = Integer.valueOf(((Long) obj).intValue());
            break;
        case DataType.FLOAT:
            result = Integer.valueOf(((Float) obj).intValue());
            break;
        case DataType.DATETIME:
            result = Integer.valueOf(Long.valueOf(((DateTime) obj).getMillis()).intValue());
            break;
        case DataType.CHARARRAY:
            result = CastUtils.stringToInteger((String) obj);
            break;
        case DataType.BIGINTEGER:
            result = Integer.valueOf(((BigInteger) obj).intValue());
            break;
        case DataType.BIGDECIMAL:
            result = Integer.valueOf(((BigDecimal) obj).intValue());
            break;
        default:
            throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT);
        }
        break;
    case DataType.DOUBLE:
        switch (DataType.findType(obj)) {
        case DataType.BYTEARRAY:
            if (null != caster) {
                result = caster.bytesToDouble(((DataByteArray) obj).get());
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "double.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
            break;
        case DataType.BOOLEAN:
            if ((Boolean) obj) {
                result = new Double(1);
            } else {
                result = new Double(1);
            }
            break;
        case DataType.INTEGER:
            result = new Double(((Integer) obj).doubleValue());
            break;
        case DataType.DOUBLE:
            result = (Double) obj;
            break;
        case DataType.LONG:
            result = new Double(((Long) obj).doubleValue());
            break;
        case DataType.FLOAT:
            result = new Double(((Float) obj).doubleValue());
            break;
        case DataType.DATETIME:
            result = new Double(Long.valueOf(((DateTime) obj).getMillis()).doubleValue());
            break;
        case DataType.CHARARRAY:
            result = CastUtils.stringToDouble((String) obj);
            break;
        case DataType.BIGINTEGER:
            result = Double.valueOf(((BigInteger) obj).doubleValue());
            break;
        case DataType.BIGDECIMAL:
            result = Double.valueOf(((BigDecimal) obj).doubleValue());
            break;
        default:
            throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT);
        }
        break;
    case DataType.LONG:
        switch (DataType.findType(obj)) {
        case DataType.BYTEARRAY:
            if (null != caster) {
                result = caster.bytesToLong(((DataByteArray) obj).get());
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "long.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
            break;
        case DataType.BOOLEAN:
            if ((Boolean) obj) {
                result = Long.valueOf(1);
            } else {
                result = Long.valueOf(0);
            }
            break;
        case DataType.INTEGER:
            result = Long.valueOf(((Integer) obj).longValue());
            break;
        case DataType.DOUBLE:
            result = Long.valueOf(((Double) obj).longValue());
            break;
        case DataType.LONG:
            result = (Long) obj;
            break;
        case DataType.FLOAT:
            result = Long.valueOf(((Float) obj).longValue());
            break;
        case DataType.DATETIME:
            result = Long.valueOf(((DateTime) obj).getMillis());
            break;
        case DataType.CHARARRAY:
            result = CastUtils.stringToLong((String) obj);
            break;
        case DataType.BIGINTEGER:
            result = Long.valueOf(((BigInteger) obj).longValue());
            break;
        case DataType.BIGDECIMAL:
            result = Long.valueOf(((BigDecimal) obj).longValue());
            break;
        default:
            throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT);
        }
        break;
    case DataType.FLOAT:
        switch (DataType.findType(obj)) {
        case DataType.BYTEARRAY:
            if (null != caster) {
                result = caster.bytesToFloat(((DataByteArray) obj).get());
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "float.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
            break;
        case DataType.BOOLEAN:
            if ((Boolean) obj) {
                result = new Float(1);
            } else {
                result = new Float(0);
            }
            break;
        case DataType.INTEGER:
            result = new Float(((Integer) obj).floatValue());
            break;
        case DataType.DOUBLE:
            result = new Float(((Double) obj).floatValue());
            break;
        case DataType.LONG:
            result = new Float(((Long) obj).floatValue());
            break;
        case DataType.FLOAT:
            result = obj;
            break;
        case DataType.DATETIME:
            result = new Float(Long.valueOf(((DateTime) obj).getMillis()).floatValue());
            break;
        case DataType.CHARARRAY:
            result = CastUtils.stringToFloat((String) obj);
            break;
        case DataType.BIGINTEGER:
            result = Float.valueOf(((BigInteger) obj).floatValue());
            break;
        case DataType.BIGDECIMAL:
            result = Float.valueOf(((BigDecimal) obj).floatValue());
            break;
        default:
            throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT);
        }
        break;
    case DataType.DATETIME:
        switch (DataType.findType(obj)) {
        case DataType.BYTEARRAY:
            if (null != caster) {
                result = caster.bytesToDateTime(((DataByteArray) obj).get());
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "datetime.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
            break;
        case DataType.INTEGER:
            result = new DateTime(((Integer) obj).longValue());
            break;
        case DataType.DOUBLE:
            result = new DateTime(((Double) obj).longValue());
            break;
        case DataType.LONG:
            result = new DateTime(((Long) obj).longValue());
            break;
        case DataType.FLOAT:
            result = new DateTime(((Float) obj).longValue());
            break;
        case DataType.DATETIME:
            result = (DateTime) obj;
            break;
        case DataType.CHARARRAY:
            result = ToDate.extractDateTime((String) obj);
            break;
        case DataType.BIGINTEGER:
            result = new DateTime(((BigInteger) obj).longValue());
            break;
        case DataType.BIGDECIMAL:
            result = new DateTime(((BigDecimal) obj).longValue());
            break;
        default:
            throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT);
        }
        break;
    case DataType.CHARARRAY:
        switch (DataType.findType(obj)) {
        case DataType.BYTEARRAY:
            if (null != caster) {
                result = caster.bytesToCharArray(((DataByteArray) obj).get());
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "float.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
            break;
        case DataType.BOOLEAN:
            if ((Boolean) obj) {
                //result = "1";
                result = Boolean.TRUE.toString();
            } else {
                //result = "0";
                result = Boolean.FALSE.toString();
            }
            break;
        case DataType.INTEGER:
            result = ((Integer) obj).toString();
            break;
        case DataType.DOUBLE:
            result = ((Double) obj).toString();
            break;
        case DataType.LONG:
            result = ((Long) obj).toString();
            break;
        case DataType.FLOAT:
            result = ((Float) obj).toString();
            break;
        case DataType.DATETIME:
            result = ((DateTime) obj).toString();
            break;
        case DataType.CHARARRAY:
            result = obj;
            break;
        case DataType.BIGINTEGER:
            result = ((BigInteger) obj).toString();
            break;
        case DataType.BIGDECIMAL:
            result = ((BigDecimal) obj).toString();
            break;
        default:
            throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT);
        }
        break;
    case DataType.BIGINTEGER:
        switch (DataType.findType(obj)) {
        case DataType.BYTEARRAY:
            if (null != caster) {
                result = caster.bytesToBigInteger(((DataByteArray) obj).get());
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "BigInteger.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
            break;
        case DataType.BOOLEAN:
            if ((Boolean) obj) {
                result = BigInteger.ONE;
            } else {
                result = BigInteger.ZERO;
            }
            break;
        case DataType.INTEGER:
            result = BigInteger.valueOf(((Integer) obj).longValue());
            break;
        case DataType.DOUBLE:
            result = BigInteger.valueOf(((Double) obj).longValue());
            break;
        case DataType.LONG:
            result = BigInteger.valueOf(((Long) obj).longValue());
            break;
        case DataType.FLOAT:
            result = BigInteger.valueOf(((Float) obj).longValue());
            break;
        case DataType.CHARARRAY:
            result = new BigInteger((String) obj);
            break;
        case DataType.BIGINTEGER:
            result = (BigInteger) obj;
            break;
        case DataType.BIGDECIMAL:
            result = ((BigDecimal) obj).toBigInteger();
            break;
        case DataType.DATETIME:
            result = BigInteger.valueOf(((DateTime) obj).getMillis());
            break;
        default:
            throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT);
        }
    case DataType.BIGDECIMAL:
        switch (DataType.findType(obj)) {
        case DataType.BYTEARRAY:
            if (null != caster) {
                result = caster.bytesToBigDecimal(((DataByteArray) obj).get());
            } else {
                int errCode = 1075;
                String msg = unknownByteArrayErrorMessage + "BigDecimal.";
                throw new ExecException(msg, errCode, PigException.INPUT);
            }
            break;
        case DataType.BOOLEAN:
            if ((Boolean) obj) {
                result = BigDecimal.ONE;
            } else {
                result = BigDecimal.ZERO;
            }
            break;
        case DataType.INTEGER:
            result = BigDecimal.valueOf(((Integer) obj).longValue());
            break;
        case DataType.DOUBLE:
            result = BigDecimal.valueOf(((Double) obj).doubleValue());
            break;
        case DataType.LONG:
            result = BigDecimal.valueOf(((Long) obj).longValue());
            break;
        case DataType.FLOAT:
            result = BigDecimal.valueOf(((Float) obj).doubleValue());
            break;
        case DataType.CHARARRAY:
            result = new BigDecimal((String) obj);
            break;
        case DataType.BIGINTEGER:
            result = new BigDecimal((BigInteger) obj);
            break;
        case DataType.BIGDECIMAL:
            result = (BigDecimal) obj;
            break;
        case DataType.DATETIME:
            result = BigDecimal.valueOf(((DateTime) obj).getMillis());
            break;
        default:
            throw new ExecException("Cannot convert " + obj + " to " + fs, 1120, PigException.INPUT);
        }
    default:
        throw new ExecException("Don't know how to convert " + obj + " to " + fs, 1120, PigException.INPUT);
    }
    return result;
}

From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * @see org.kuali.ole.module.purap.service.PurapAccountingService#convertMoneyToPercent(org.kuali.ole.module.purap.document.PaymentRequestDocument)
 *///from  www . j a v  a  2 s  .  c  om
@Override
public void convertMoneyToPercent(PaymentRequestDocument pr) {
    LOG.debug("convertMoneyToPercent() started");

    int itemNbr = 0;

    for (Iterator<PaymentRequestItem> iter = pr.getItems().iterator(); iter.hasNext();) {
        PaymentRequestItem item = iter.next();

        itemNbr++;
        String identifier = item.getItemIdentifierString();

        if (item.getTotalAmount() != null && item.getTotalAmount().isNonZero()) {
            int numOfAccounts = item.getSourceAccountingLines().size();
            BigDecimal percentTotal = BigDecimal.ZERO;
            KualiDecimal accountTotal = KualiDecimal.ZERO;
            int accountIdentifier = 0;

            KualiDecimal addChargeItem = KualiDecimal.ZERO;
            KualiDecimal lineItemPreTaxTotal = KualiDecimal.ZERO;
            /* KualiDecimal prorateSurcharge = KualiDecimal.ZERO;
             if (item.getItemType().isQuantityBasedGeneralLedgerIndicator() && item.getExtendedPrice() != null && item.getExtendedPrice().compareTo(KualiDecimal.ZERO) != 0) {
            if (((OlePaymentRequestItem) item).getItemSurcharge() != null) {
                prorateSurcharge = new KualiDecimal(((OlePaymentRequestItem) item).getItemSurcharge()).multiply(item.getItemQuantity());
            }
             }*/
            PurApAccountingLine lastAccount = null;
            BigDecimal accountTotalPercent = BigDecimal.ZERO;

            for (PurApAccountingLine purApAccountingLine : item.getSourceAccountingLines()) {
                accountIdentifier++;
                PaymentRequestAccount account = (PaymentRequestAccount) purApAccountingLine;

                // account.getAmount returns the wrong value for trade in source accounting lines...
                KualiDecimal accountAmount = KualiDecimal.ZERO;
                if (ObjectUtils.isNotNull(account.getAmount())) {
                    accountAmount = account.getAmount();
                }

                BigDecimal tmpPercent = BigDecimal.ZERO;
                KualiDecimal extendedPrice = item.getTotalAmount();
                tmpPercent = accountAmount.bigDecimalValue().divide(extendedPrice.bigDecimalValue(),
                        PurapConstants.CREDITMEMO_PRORATION_SCALE.intValue(), KualiDecimal.ROUND_BEHAVIOR);

                if (accountIdentifier == numOfAccounts) {
                    // if on last account, calculate the percent by subtracting current percent total from 1
                    tmpPercent = BigDecimal.ONE.subtract(percentTotal);
                }

                // test that the above amount is correct, if so just check that the total of all these matches the item total
                BigDecimal calcAmountBd = tmpPercent.multiply(extendedPrice.bigDecimalValue());
                calcAmountBd = calcAmountBd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR);
                KualiDecimal calcAmount = new KualiDecimal(calcAmountBd);
                //calcAmount = calcAmount.subtract(prorateSurcharge);
                if (calcAmount.compareTo(accountAmount) != 0) {
                    // rounding error
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("convertMoneyToPercent() Rounding error on " + account);
                    }
                    String param1 = identifier + "." + accountIdentifier;
                    String param2 = calcAmount.bigDecimalValue().subtract(accountAmount.bigDecimalValue())
                            .toString();
                    GlobalVariables.getMessageMap().putError(item.getItemIdentifierString(),
                            PurapKeyConstants.ERROR_ITEM_ACCOUNTING_ROUNDING, param1, param2);
                    account.setAmount(calcAmount);
                }

                // update percent
                if (LOG.isDebugEnabled()) {
                    LOG.debug("convertMoneyToPercent() updating percent to " + tmpPercent);
                }
                account.setAccountLinePercent(tmpPercent.multiply(new BigDecimal(100)));
                accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent());
                lastAccount = account;
                // check total based on adjusted amount
                accountTotal = accountTotal.add(calcAmount);
                percentTotal = percentTotal.add(tmpPercent);
            }
            BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent)
                    .setScale(BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING);
            if (ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) {
                KualiDecimal differencePercent = (((new KualiDecimal(accountTotalPercent))
                        .subtract(new KualiDecimal(100))).abs());
                if ((differencePercent.abs()).isLessEqual(
                        new KualiDecimal(1).multiply((new KualiDecimal(item.getSourceAccountingLines().size())
                                .divide(new KualiDecimal(2)))))) {
                    lastAccount
                            .setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference));
                } else {
                    lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent());
                }
            }
        }
    }
}

From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java

@Override
public void convertMoneyToPercent(InvoiceDocument inv) {
    LOG.debug("convertMoneyToPercent() started");

    int itemNbr = 0;

    for (Iterator<InvoiceItem> iter = inv.getItems().iterator(); iter.hasNext();) {
        InvoiceItem item = iter.next();/*  ww w.ja  v  a 2  s .com*/

        itemNbr++;
        String identifier = item.getItemIdentifierString();

        if (item.getTotalAmount() != null && item.getTotalAmount().isNonZero()) {
            int numOfAccounts = item.getSourceAccountingLines().size();
            BigDecimal percentTotal = BigDecimal.ZERO;
            KualiDecimal accountTotal = KualiDecimal.ZERO;
            int accountIdentifier = 0;

            KualiDecimal addChargeItem = KualiDecimal.ZERO;
            KualiDecimal lineItemPreTaxTotal = KualiDecimal.ZERO;
            KualiDecimal prorateSurcharge = KualiDecimal.ZERO;
            if (item.getItemType().isQuantityBasedGeneralLedgerIndicator() && item.getExtendedPrice() != null
                    && item.getExtendedPrice().compareTo(KualiDecimal.ZERO) != 0) {
                if (((OleInvoiceItem) item).getItemSurcharge() != null) {
                    prorateSurcharge = new KualiDecimal(((OleInvoiceItem) item).getItemSurcharge())
                            .multiply(item.getItemQuantity());
                }
            }
            PurApAccountingLine lastAccount = null;
            BigDecimal accountTotalPercent = BigDecimal.ZERO;
            for (PurApAccountingLine purApAccountingLine : item.getSourceAccountingLines()) {
                accountIdentifier++;
                InvoiceAccount account = (InvoiceAccount) purApAccountingLine;

                // account.getAmount returns the wrong value for trade in source accounting lines...
                KualiDecimal accountAmount = KualiDecimal.ZERO;
                if (ObjectUtils.isNotNull(account.getAmount())) {
                    accountAmount = account.getAmount();
                }

                BigDecimal tmpPercent = BigDecimal.ZERO;
                KualiDecimal extendedPrice = item.getTotalAmount();
                tmpPercent = accountAmount.bigDecimalValue().divide(extendedPrice.bigDecimalValue(),
                        PurapConstants.CREDITMEMO_PRORATION_SCALE.intValue(), KualiDecimal.ROUND_BEHAVIOR);

                if (accountIdentifier == numOfAccounts) {
                    // if on last account, calculate the percent by subtracting current percent total from 1
                    tmpPercent = BigDecimal.ONE.subtract(percentTotal);
                }

                // test that the above amount is correct, if so just check that the total of all these matches the item total
                BigDecimal calcAmountBd = tmpPercent.multiply(extendedPrice.bigDecimalValue());
                calcAmountBd = calcAmountBd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR);
                KualiDecimal calcAmount = new KualiDecimal(calcAmountBd);
                calcAmount = calcAmount.subtract(prorateSurcharge);
                if (calcAmount.compareTo(accountAmount) != 0) {
                    // rounding error
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("convertMoneyToPercent() Rounding error on " + account);
                    }
                    String param1 = identifier + "." + accountIdentifier;
                    String param2 = calcAmount.bigDecimalValue().subtract(accountAmount.bigDecimalValue())
                            .toString();
                    GlobalVariables.getMessageMap().putError(item.getItemIdentifierString(),
                            PurapKeyConstants.ERROR_ITEM_ACCOUNTING_ROUNDING, param1, param2);
                    account.setAmount(calcAmount);
                }

                // update percent
                if (LOG.isDebugEnabled()) {
                    LOG.debug("convertMoneyToPercent() updating percent to " + tmpPercent);
                }
                account.setAccountLinePercent(tmpPercent.multiply(new BigDecimal(100)));
                accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent());
                lastAccount = account;

                // check total based on adjusted amount
                accountTotal = accountTotal.add(calcAmount);
                percentTotal = percentTotal.add(tmpPercent);
            }
            BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent)
                    .setScale(BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING);
            if (ObjectUtils.isNotNull(lastAccount)
                    && ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) {
                KualiDecimal differencePercent = (((new KualiDecimal(accountTotalPercent))
                        .subtract(new KualiDecimal(100))).abs());
                if ((differencePercent.abs()).isLessEqual(
                        new KualiDecimal(1).multiply((new KualiDecimal(item.getSourceAccountingLines().size())
                                .divide(new KualiDecimal(2)))))) {
                    lastAccount
                            .setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference));
                } else {
                    lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent());
                }
            }
        }
    }
}

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

/**
 * Riemann zeta function./*from  w w  w .  j av a2s . co m*/
 *
 * @param n  The positive integer argument.
 *           32
 * @param mc Specification of the accuracy of the result.
 * @return zeta(n).
 */
static public BigDecimal zeta(final int n, final MathContext mc) {
    if (n <= 0) {
        throw new ProviderException("Unimplemented zeta at negative argument " + n);
    }

    if (n == 1) {
        throw new ArithmeticException("Pole at zeta(1) ");
    }

    if (n % 2 == 0) {
        /* Even indices. Abramowitz-Stegun 23.2.16. Start with 2^(n-1)*B(n)/n!
         */
        Rational b = (new Bernoulli()).at(n).abs();
        b = b.divide((new Factorial()).at(n));
        b = b.multiply(BigInteger.ONE.shiftLeft(n - 1));
        /* to be multiplied by pi^n. Absolute error in the result of pi^n is n times
         * error in pi times pi^(n-1). Relative error is n*error(pi)/pi, requested by mc.
         * Need one more digit in pi if n=10, two digits if n=100 etc, and add one extra digit.
         */
        MathContext mcpi = new MathContext(mc.getPrecision() + (int) (Math.log10(10.0 * n)));
        final BigDecimal piton = pi(mcpi).pow(n, mc);

        return multiplyRound(piton, b);

    } else if (n == 3) {
        /* Broadhurst BBP \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}
         * Error propagation: S31 is roughly 0.087, S33 roughly 0.131
         */
        int[] a31 = { 1, -7, -1, 10, -1, -7, 1, 0 };

        int[] a33 = { 1, 1, -1, -2, -1, 1, 1, 0 };
        BigDecimal S31 = broadhurstBBP(3, 1, a31, mc);
        BigDecimal S33 = broadhurstBBP(3, 3, a33, mc);
        S31 = S31.multiply(new BigDecimal(48));
        S33 = S33.multiply(new BigDecimal(32));

        return S31.add(S33).divide(new BigDecimal(7), mc);

    } else if (n == 5) {
        /* Broadhurst BBP \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}
         * Error propagation: S51 is roughly -11.15, S53 roughly 22.165, S55 is roughly 0.031
         * 9*2048*S51/6265 = -3.28. 7*2038*S53/61651= 5.07. 738*2048*S55/61651= 0.747.
         * The result is of the order 1.03, so we add 2 digits to S51 and S52 and one digit to S55.
         */
        int[] a51 = { 31, -1614, -31, -6212, -31, -1614, 31, 74552 };

        int[] a53 = { 173, 284, -173, -457, -173, 284, 173, -111 };

        int[] a55 = { 1, 0, -1, -1, -1, 0, 1, 1 };
        BigDecimal S51 = broadhurstBBP(5, 1, a51, new MathContext(2 + mc.getPrecision()));
        BigDecimal S53 = broadhurstBBP(5, 3, a53, new MathContext(2 + mc.getPrecision()));
        BigDecimal S55 = broadhurstBBP(5, 5, a55, new MathContext(1 + mc.getPrecision()));
        S51 = S51.multiply(new BigDecimal(18432));
        S53 = S53.multiply(new BigDecimal(14336));
        S55 = S55.multiply(new BigDecimal(1511424));

        return S51.add(S53).subtract(S55).divide(new BigDecimal(62651), mc);

    } else {
        /* Cohen et al Exp Math 1 (1) (1992) 25
         */
        Rational betsum = new Rational();
        Bernoulli bern = new Bernoulli();
        Factorial fact = new Factorial();

        for (int npr = 0; npr <= (n + 1) / 2; npr++) {
            Rational b = bern.at(2 * npr).multiply(bern.at(n + 1 - 2 * npr));
            b = b.divide(fact.at(2 * npr)).divide(fact.at(n + 1 - 2 * npr));
            b = b.multiply(1 - 2 * npr);

            if (npr % 2 == 0) {
                betsum = betsum.add(b);
            } else {
                betsum = betsum.subtract(b);
            }

        }
        betsum = betsum.divide(n - 1);
        /* The first term, including the facor (2pi)^n, is essentially most
         * of the result, near one. The second term below is roughly in the range 0.003 to 0.009.
         * So the precision here is matching the precisionn requested by mc, and the precision
         * requested for 2*pi is in absolute terms adjusted.
         */
        MathContext mcloc = new MathContext(2 + mc.getPrecision() + (int) (Math.log10((double) (n))));
        BigDecimal ftrm = pi(mcloc).multiply(new BigDecimal(2));
        ftrm = ftrm.pow(n);

        ftrm = multiplyRound(ftrm, betsum.BigDecimalValue(mcloc));
        BigDecimal exps = new BigDecimal(0);
        /* the basic accuracy of the accumulated terms before multiplication with 2
         */

        double eps = Math.pow(10., -mc.getPrecision());

        if (n % 4 == 3) {
            /* since the argument n is at least 7 here, the drop
             * of the terms is at rather constant pace at least 10^-3, for example
             * 0.0018, 0.2e-7, 0.29e-11, 0.74e-15 etc for npr=1,2,3.... We want 2 times these terms
             * fall below eps/10.
             */
            int kmax = mc.getPrecision() / 3;
            eps /= kmax;
            /* need an error of eps for 2/(exp(2pi)-1) = 0.0037
             * The absolute error is 4*exp(2pi)*err(pi)/(exp(2pi)-1)^2=0.0075*err(pi)
             */
            BigDecimal exp2p = pi(new MathContext(3 + err2prec(3.14, eps / 0.0075)));
            exp2p = exp(exp2p.multiply(new BigDecimal(2)));
            BigDecimal c = exp2p.subtract(BigDecimal.ONE);
            exps = divideRound(1, c);

            for (int npr = 2; npr <= kmax; npr++) {
                /* the error estimate above for npr=1 is the worst case of
                 * the absolute error created by an error in 2pi. So we can
                 * safely re-use the exp2p value computed above without
                 * reassessment of its error.
                 */
                c = powRound(exp2p, npr).subtract(BigDecimal.ONE);
                c = multiplyRound(c, (new BigInteger("" + npr)).pow(n));
                c = divideRound(1, c);
                exps = exps.add(c);

            }
        } else {
            /* since the argument n is at least 9 here, the drop
             * of the terms is at rather constant pace at least 10^-3, for example
             * 0.0096, 0.5e-7, 0.3e-11, 0.6e-15 etc. We want these terms
             * fall below eps/10.
             */
            int kmax = (1 + mc.getPrecision()) / 3;
            eps /= kmax;
            /* need an error of eps for 2/(exp(2pi)-1)*(1+4*Pi/8/(1-exp(-2pi)) = 0.0096
             * at k=7 or = 0.00766 at k=13 for example.
             * The absolute error is 0.017*err(pi) at k=9, 0.013*err(pi) at k=13, 0.012 at k=17
             */
            BigDecimal twop = pi(new MathContext(3 + err2prec(3.14, eps / 0.017)));
            twop = twop.multiply(new BigDecimal(2));
            BigDecimal exp2p = exp(twop);
            BigDecimal c = exp2p.subtract(BigDecimal.ONE);
            exps = divideRound(1, c);
            c = BigDecimal.ONE.subtract(divideRound(1, exp2p));
            c = divideRound(twop, c).multiply(new BigDecimal(2));
            c = divideRound(c, n - 1).add(BigDecimal.ONE);
            exps = multiplyRound(exps, c);

            for (int npr = 2; npr <= kmax; npr++) {
                c = powRound(exp2p, npr).subtract(BigDecimal.ONE);
                c = multiplyRound(c, (new BigInteger("" + npr)).pow(n));
                BigDecimal d = divideRound(1, exp2p.pow(npr));
                d = BigDecimal.ONE.subtract(d);
                d = divideRound(twop, d).multiply(new BigDecimal(2 * npr));
                d = divideRound(d, n - 1).add(BigDecimal.ONE);
                d = divideRound(d, c);
                exps = exps.add(d);

            }
        }
        exps = exps.multiply(new BigDecimal(2));

        return ftrm.subtract(exps, mc);

    }
}

From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 * @param empcntClientProjectDataList// w  ww  .  j  av  a 2 s  .  c  o  m
 * @param empClientProjectTeamStructList
 * @param employee
 * @param month
 * @param year
 * @param costCentre
 * @param countType
 * @param allignedTimeZero
 * @param assistedTimeZero
 * @param apportionedTimeZero
 * @param allignedTimeOne
 * @param totalTimeOne
 */
private void getSingleProjectDetail(List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList,
        List<EmpClientProjectTeamStruct> empClientProjectTeamStructList, EmployeeMaster employee,
        TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType,
        BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeZero,
        BigDecimal allignedTimeOne, BigDecimal totalTimeOne, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    /*
     * Also assign to assisted if project detail present in both assigned
     * and unassigned list
     * 
     * Note : Only in unassigned project . do the remaining count as per
     * revenue to apportion
     * 
     * If not present in revenue table then go to zero project details
     */
    logger.debug("<====getSingleProjectDetail START====>");
    Integer employeeId = employee.getEmployeeId();
    Integer yearId = year.getYearId();
    Integer monthId = month.getMonthId();
    String costCentreId = costCentre.getCostCentreId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    logger.debug("getSingleProjectDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::"
            + costCentreId + "::" + deviderHour);

    // Get project details
    Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) {
        employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(),
                empClientProjectTeamStructThree);
    }

    validEmployeeProjectIds.putAll(employeeProjectIds);
    // logger.debug("validEmployeeProjectIds 1:size===>" +
    // validEmployeeProjectIds.size());

    // check in revenue table
    for (Integer key : employeeProjectIds.keySet()) {
        EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key);
        List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(),
                        mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(),
                        costCentre.getCostCentreId());
        if (listValues.isEmpty()) {
            validEmployeeProjectIds.remove(key);
        }
    }
    // logger.debug("validEmployeeProjectIds 2:size===>" +
    // validEmployeeProjectIds.size());
    if (validEmployeeProjectIds.isEmpty()) {
        getZeroProjectsDetail(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                empCloseCntClientProjectDataList, employee, month, year, costCentre, countType,
                allignedTimeZero, assistedTimeZero, totalTimeOne, totalTimeOne, countTypeId,
                employeePcTagsTeamStructMap);
    }
    // Get list of project from execution data for that employee
    List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId,
            costCentreId);
    // logger.debug("execution data projects===>" + projectIdList.size());

    if (projectIdList.isEmpty()) {
        // logger.debug("Contain InValid projects :(Assign count one)===>");

        for (Integer projectId : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
            // logger.debug("978: Contain InValid projects :(Assign count one)===>"+1);
            EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                    mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                    costCentre, allignedTimeOne, assistedTimeZero, apportionedTimeZero, allignedTimeOne);
            if (countTypeId == 1) {
                empOpenCntClientProjectDataList.add(empcntClientProjectData);
            } else if (countTypeId == 2) {
                empCloseCntClientProjectDataList.add(empcntClientProjectData);
            }
        }
    } else {
        // logger.debug("Else Contain Valid projects===>");
        Integer validEmployeeProjectCount = validEmployeeProjectIds.size();
        // Get valid projects list=>project is both revenue data and
        // execution data
        Set<Integer> validAllProjects = new HashSet<Integer>();
        for (Integer projectId : projectIdList) {
            List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                    .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId);
            if (!listValues.isEmpty()) {
                validAllProjects.add(projectId);
            }

        }
        Integer validAllProjectCount = validAllProjects.size();
        // logger.debug("validAllProjects :size===>" +
        // validAllProjects.size());
        // Total hour worked by an Employee
        List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId,
                yearId, monthId, costCentreId);
        BigDecimal toatlTime = toatalHours.get(0);
        // logger.debug("ToatalHours===>" + toatlTime);

        // Separate assigned projects from execution data projects
        Map<Integer, BigDecimal> assignedProjects = new HashMap<Integer, BigDecimal>();
        Map<Integer, BigDecimal> unAssignedProjects = new HashMap<Integer, BigDecimal>();
        List<Object[]> allProjectTimeList = executionDataDao
                .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId);
        for (Object[] result : allProjectTimeList) {
            Integer projectId = (Integer) result[0];
            BigDecimal hour = (BigDecimal) result[1];
            Integer companyId = (Integer) result[2];
            if (validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("UnAssignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                assignedProjects.put(projectId, hour);
            }
            if (!validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("assignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                unAssignedProjects.put(projectId, hour);
            }
        }
        if (validEmployeeProjectCount == 1 && validAllProjectCount == 1
                && validAllProjects.containsAll(validEmployeeProjectIds.keySet())
                && unAssignedProjects.isEmpty()) {

            // logger.debug("validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)");
            for (Integer key : assignedProjects.keySet()) {
                // Get time spent on each project by employee id
                Integer projectId = key;
                EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                // logger.debug("1034 :validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)===>1");
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                        costCentre, allignedTimeOne, assistedTimeZero, apportionedTimeZero, allignedTimeOne);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }

        } else if (!assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("1047 : Both in assigned and unassigned projects===>");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug("Worked hours===> >=168");
                for (Integer key : assignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1056 :assigned:(Both in assigned and unassigned projects===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1073 :unassigned :(Both in assigned and unassigned projects===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // Assign to assisted count for unAssignedProjects
                    Integer projectId = key;
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("769: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                totalUnAssingnedHours = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                for (Map.Entry<Integer, BigDecimal> entry : assignedProjects.entrySet()) {
                    assingnedHours = assingnedHours.add(entry.getValue());
                }

                // logger.debug("assingnedHours===> "+assingnedHours);
                for (Integer key : assignedProjects.keySet()) {
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    // logger.debug("1119 :projectId : timeByProject===> "+projectId+" : "+timeByProject);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal averageWorkedHours = timeByProject.divide(assingnedHours, 2,
                            RoundingMode.HALF_EVEN);
                    // logger.debug("1121 :assingnedHours : totalUnAssingnedHours===> "+assingnedHours+" : "+totalUnAssingnedHours);
                    BigDecimal actualWorkedHours = averageWorkedHours.multiply(totalUnAssingnedHours);
                    actualWorkedHours = actualWorkedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1124 :averageWorkedHours : actualWorkedHours===> "+averageWorkedHours+" : "+actualWorkedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, actualWorkedHours, assistedTimeZero, apportionedTimeZero,
                            actualWorkedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            }
        }

        else if (assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("In  unassigned projects only===>");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug("Worked hours===> >=168");
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1148 :In unassigned projects only===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);

                    // Assign to assisted count for unAssignedProjects
                    Integer projectId = key;
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("1173: Assisted hours (In unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                logger.debug("1209 totalUnAssingnedHours===> " + totalUnAssingnedHours);

                BigDecimal remainProportion = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                logger.debug("remainProportion===> " + remainProportion);
                getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                        employee, month, year, costCentre, countType, remainProportion, unAssignedProjects,
                        countTypeId, employeePcTagsTeamStructMap);

            }
        }

    }
    // logger.debug("<====getSingleProjectDetail END====>");
}

From source file:org.marketcetera.strategy.LanguageTestBase.java

/**
 * Tests a strategy's ability to cancel an existing order and replace it with a new one.
 *
 * @throws Exception if an error occurs//from ww w .ja  v  a  2 s.  co m
 */
@Test
public void cancelReplace() throws Exception {
    MockRecorderModule recorder = MockRecorderModule.Factory.recorders.get(outputURN);
    assertNotNull("Must be able to find the recorder created", recorder);
    // for now, forbid the creation of execution reports
    MockRecorderModule.shouldSendExecutionReports = false;
    // set up data for the orders to be created
    // set price
    AbstractRunningStrategy.setProperty("price", "100.23");
    // add quantity
    AbstractRunningStrategy.setProperty("quantity", "10000");
    // add side
    AbstractRunningStrategy.setProperty("side", Side.Buy.name());
    // add symbol
    AbstractRunningStrategy.setProperty("symbol", "METC");
    // add time-in-force
    AbstractRunningStrategy.setProperty("timeInForce", TimeInForce.Day.toString());
    // add type
    AbstractRunningStrategy.setProperty("orderType", OrderType.Market.name());
    // create a strategy to use as our test vehicle
    ModuleURN strategy = generateOrders(getOrdersStrategy(), outputURN);
    AbstractRunningStrategy runningStrategy = (AbstractRunningStrategy) getRunningStrategy(strategy)
            .getRunningStrategy();
    // submit an order
    assertNull(AbstractRunningStrategy.getProperty("orderID"));
    runningStrategy.onAsk(askEvent);
    // save the orderID of the order we created, we'll need it later
    String orderIDString = AbstractRunningStrategy.getProperty("orderID");
    assertEquals(1, runningStrategy.getSubmittedOrders().size());
    assertEquals(OrderType.Market, runningStrategy.getSubmittedOrders().iterator().next().getOrderType());
    assertNotNull(orderIDString);
    // try to cancel/replace with a null OrderID
    AbstractRunningStrategy.setProperty("orderID", null);
    AbstractRunningStrategy.setProperty("newOrderID", "");
    OrderSingle newOrder = Factory.getInstance().createOrderSingle();
    assertNotNull(AbstractRunningStrategy.getProperty("newOrderID"));
    BigDecimal quantity = new BigDecimal("1000.50");
    newOrder.setQuantity(quantity);
    newOrder.setPrice(new BigDecimal("1"));
    newOrder.setTimeInForce(TimeInForce.GoodTillCancel);
    newOrder.setInstrument(new Equity("METC"));
    // try to cancel/replace with a null OrderID
    runningStrategy.onOther(newOrder);
    assertNull(AbstractRunningStrategy.getProperty("newOrderID"));
    // try to cancel/replace with an unsubmitted OrderID
    OrderID unsubmittedOrderID = new OrderID("this-order-id-does-not-exist-" + System.nanoTime());
    AbstractRunningStrategy.setProperty("orderID", unsubmittedOrderID.toString());
    AbstractRunningStrategy.setProperty("newOrderID", "");
    assertNotNull(AbstractRunningStrategy.getProperty("newOrderID"));
    runningStrategy.onOther(newOrder);
    assertNull(AbstractRunningStrategy.getProperty("newOrderID"));
    // try with a null replacement order
    // put back the orderID of the order to replace
    AbstractRunningStrategy.setProperty("orderID", orderIDString);
    AbstractRunningStrategy.setProperty("newOrderID", "");
    runningStrategy.onOther("");
    assertNull(StringUtils.trimToNull(AbstractRunningStrategy.getProperty("newOrderID")));
    // now allow the cancel/replace to succeed
    // make sure the order is open before we begin
    MockRecorderModule.shouldSendExecutionReports = true;
    MockRecorderModule.shouldFullyFillOrders = false;
    StrategyTestBase.executionReportMultiplicity = 1;
    newOrder.setOrderID(new OrderID(orderIDString));
    List<ExecutionReport> reports = generateExecutionReports(newOrder);
    for (ExecutionReport report : reports) {
        runningStrategy.onExecutionReportRedirected(report);
    }
    runningStrategy.onOther(newOrder);
    String replaceIDString = AbstractRunningStrategy.getProperty("newOrderID");
    assertNotNull(replaceIDString);
    assertFalse(replaceIDString.equals(newOrder.getOrderID().toString()));
    // hooray, it worked
    // send a new order
    runningStrategy.onAsk(askEvent);
    orderIDString = AbstractRunningStrategy.getProperty("orderID");
    assertNotNull(orderIDString);
    AbstractRunningStrategy.setProperty("orderID", orderIDString);
    // cause a cancel/replace again, but this time don't allow the cancel/replace to be submitted
    recorder.resetDataReceived();
    AbstractRunningStrategy.setProperty("skipSubmitOrders", "true");
    runningStrategy.onOther(newOrder);
    assertNotNull(replaceIDString);
    assertTrue(recorder.getDataReceived().isEmpty());
    // can't cancel/replace this order any more, so create a new one
    runningStrategy.onAsk(askEvent);
    recorder.resetDataReceived();
    orderIDString = AbstractRunningStrategy.getProperty("orderID");
    assertNotNull(orderIDString);
    AbstractRunningStrategy.setProperty("orderID", orderIDString);
    // cancel/replace this order, don't automatically submit it, then modify it and submit it manually
    AbstractRunningStrategy.setProperty("delaySubmitOrders", "true");
    newOrder.setOrderType(OrderType.Market);
    runningStrategy.onOther(newOrder);
    assertNotNull(replaceIDString);
    assertEquals(recorder.getDataReceived().toString(), 1, recorder.getDataReceived().size());
    Object receivedData = recorder.getDataReceived().get(0).getData();
    assertTrue("Object is " + receivedData, receivedData instanceof OrderReplace);
    OrderReplace receivedOrder = (OrderReplace) receivedData;
    assertNull(receivedOrder.getBrokerOrderID());
    assertEquals(quantity.add(BigDecimal.ONE), receivedOrder.getQuantity());
    AbstractRunningStrategy.setProperty("delaySubmitOrders", null);
    AbstractRunningStrategy.setProperty("skipSubmitOrders", null);
    // turn on execution reports
    MockRecorderModule.shouldSendExecutionReports = true;
    MockRecorderModule.shouldFullyFillOrders = false;
    StrategyTestBase.executionReportMultiplicity = 20;
    // re-submit the order
    runningStrategy.onAsk(askEvent);
    assertNotNull(AbstractRunningStrategy.getProperty("orderID"));
    assertFalse(orderIDString.equals(AbstractRunningStrategy.getProperty("orderID")));
    AbstractRunningStrategy.setProperty("newOrderID", null);
    // cancel/replace again (this time using execution reports)
    runningStrategy.onOther(newOrder);
    assertNotNull(AbstractRunningStrategy.getProperty("newOrderID"));
    // submit an order again
    AbstractRunningStrategy.setProperty("orderID", null);
    runningStrategy.onAsk(askEvent);
    orderIDString = AbstractRunningStrategy.getProperty("orderID");
    assertNotNull(orderIDString);
    // cycle the strategy
    stopStrategy(strategy);
    startStrategy(strategy);
    runningStrategy = (AbstractRunningStrategy) getRunningStrategy(strategy).getRunningStrategy();
    AbstractRunningStrategy.setProperty("newOrderID", null);
    // try to cancel/replace again, won't work because the order to be replaced was in the last strategy session (before the stop)
    runningStrategy.onOther(newOrder);
    assertNull(AbstractRunningStrategy.getProperty("newOrderID"));
    // make sure an order replace can be submitted during strategy stop
    AbstractRunningStrategy.setProperty("orderReplaceNull", "");
    AbstractRunningStrategy.setProperty("shouldReplace", "true");
    stopStrategy(strategy);
    assertEquals("true", AbstractRunningStrategy.getProperty("orderReplaceNull"));
    // do a final test making sure that a price *is* specified for a non-market replace
    AbstractRunningStrategy.setProperty("orderType", OrderType.Limit.name());
    recorder.resetDataReceived();
    startStrategy(strategy);
    runningStrategy = (AbstractRunningStrategy) getRunningStrategy(strategy).getRunningStrategy();
    AbstractRunningStrategy.setProperty("newOrderID", null);
    runningStrategy.onAsk(askEvent);
    orderIDString = AbstractRunningStrategy.getProperty("orderID");
    assertNotNull(orderIDString);
    assertEquals(1, runningStrategy.getSubmittedOrders().size());
    assertEquals(OrderType.Limit, runningStrategy.getSubmittedOrders().iterator().next().getOrderType());
    recorder.resetDataReceived();
    AbstractRunningStrategy.setProperty("orderID", orderIDString);
    AbstractRunningStrategy.setProperty("newOrderID", "");
    newOrder.setPrice(new BigDecimal("12345"));
    runningStrategy.onOther(newOrder);
    receivedData = recorder.getDataReceived().get(0).getData();
    assertTrue("Object is " + receivedData, receivedData instanceof OrderReplace);
    receivedOrder = (OrderReplace) receivedData;
    assertEquals(new BigDecimal("12345"), receivedOrder.getPrice());
}

From source file:pe.gob.mef.gescon.web.ui.BaseLegalMB.java

public String toPost() {
    try {//ww  w.java 2 s . co  m
        this.cleanAttributes();
        int index = Integer.parseInt((String) JSFUtils.getRequestParameter("index"));
        if (!CollectionUtils.isEmpty(this.getFilteredListaBaseLegal())) {
            this.setSelectedBaseLegal(this.getFilteredListaBaseLegal().get(index));
        } else {
            this.setSelectedBaseLegal(this.getListaBaseLegal().get(index));
        }
        CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
        this.setSelectedCategoria(
                categoriaService.getCategoriaById(this.getSelectedBaseLegal().getNcategoriaid()));
        index = this.getSelectedBaseLegal().getVnumero().indexOf("-");
        this.setTiporangoId(this.getSelectedBaseLegal().getNtiporangoid());
        this.setRangoId(this.getSelectedBaseLegal().getNrangoid());
        this.setTipoNorma(this.getSelectedBaseLegal().getVnumero().substring(0, index).trim());
        this.setNumeroNorma(this.getSelectedBaseLegal().getVnumero().substring(index + 1).trim());
        this.setChkGobNacional(this.getSelectedBaseLegal().getNgobnacional().equals(BigDecimal.ONE));
        this.setChkGobRegional(this.getSelectedBaseLegal().getNgobregional().equals(BigDecimal.ONE));
        this.setChkGobLocal(this.getSelectedBaseLegal().getNgoblocal().equals(BigDecimal.ONE));
        this.setChkMancomunidades(this.getSelectedBaseLegal().getNmancomunidades().equals(BigDecimal.ONE));
        this.setChkDestacado(this.getSelectedBaseLegal().getNdestacado().equals(BigDecimal.ONE));
        this.setCodigoWiki(this.getSelectedBaseLegal().getNcodigowiki());
        ConocimientoService conocimientoService = (ConocimientoService) ServiceFinder
                .findBean("ConocimientoService");
        this.setSelectedWiki(conocimientoService.getConocimientoById(this.getCodigoWiki()));
        RangoService rangoService = (RangoService) ServiceFinder.findBean("RangoService");
        this.setListaRangos(
                new Items(rangoService.getRangosActivosByTipo(this.getSelectedBaseLegal().getNtiporangoid()),
                        null, "nrangoid", "vnombre").getItems());
        BaseLegalService service = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
        this.setListaSource(
                service.getTbaselegalesNotLinkedById(this.getSelectedBaseLegal().getNbaselegalid()));
        this.setListaTarget(service.getTbaselegalesLinkedById(this.getSelectedBaseLegal().getNbaselegalid()));
        this.setPickList(new DualListModel<BaseLegal>(this.getListaSource(), this.getListaTarget()));
        this.setFilteredListaBaseLegal(new ArrayList());
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return "/pages/baselegal/publicar?faces-redirect=true";
}

From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java

private Validator getPaymentValidator(final DoPaymentDTO payment) {
    final Validator validator = new Validator("transfer");
    Collection<TransactionContext> possibleContexts = new ArrayList<TransactionContext>();
    possibleContexts.add(TransactionContext.PAYMENT);
    if (LoggedUser.isWebService() || LoggedUser.isSystem()) {
        possibleContexts.add(TransactionContext.AUTOMATIC);
    } else {/* w  w  w  .  java  2s .c om*/
        possibleContexts.add(TransactionContext.SELF_PAYMENT);
    }
    validator.property("context").required().anyOf(possibleContexts);
    validator.property("to").required().key("payment.recipient");
    // as currency is maybe not set on the DTO, we get it from the TT in stead of directly from the DTO
    final TransferType tt = fetchService.fetch(payment.getTransferType(), Relationships.TRANSACTION_FEES,
            RelationshipHelper.nested(TransferType.Relationships.FROM, TransferType.Relationships.TO,
                    AccountType.Relationships.CURRENCY, Currency.Relationships.A_RATE_PARAMETERS),
            RelationshipHelper.nested(TransferType.Relationships.FROM, TransferType.Relationships.TO,
                    AccountType.Relationships.CURRENCY, Currency.Relationships.D_RATE_PARAMETERS));
    final Currency currency = tt == null ? null : tt.getCurrency();
    if (currency != null && (currency.isEnableARate() || currency.isEnableDRate())) {
        // if the date is not null at this moment, it is in the past, which is not allowed with rates.
        if (payment.getDate() != null) {
            validator.general(new NoPastDateWithRatesValidator());
        }
    } else {
        validator.property("date").key("payment.manualDate").past();
    }

    validator.property("ticket").add(new TicketValidation());

    addAmountValidator(validator, tt);
    validator.property("transferType").key("transfer.type").required();
    validator.property("description").maxLength(1000);
    validator.general(new SchedulingValidator());
    validator.general(new PendingContractValidator());
    if (payment.getTransferType() != null && payment.getTo() != null && payment.getAmount() != null) {

        /*
         * For user validation, we need to check if the transaction amount is high enough to cover all fees. This depends on all fees, but only in
         * case of fixed fees it makes sense to increase the transaction amount. The formula for this is: given transactionamount > (sum of fixed
         * fees )/ (1 minus sum of percentage fees expressed as fractions). This of course only applies for fees with deductAmount; fees which are
         * not deducted are excluded from this calculation.
         */
        final TransactionFeePreviewDTO preview = transactionFeeService.preview(payment.getFrom(),
                payment.getTo(), tt, payment.getAmount());
        final Property amount = validator.property("amount");
        final Collection<? extends TransactionFee> fees = preview.getFees().keySet();
        BigDecimal sumOfFixedFees = BigDecimal.ZERO;
        BigDecimal sumOfPercentageFees = BigDecimal.ZERO;
        for (final TransactionFee fee : fees) {
            if (fee.isDeductAmount()) {
                if (fee.getChargeType() == ChargeType.FIXED) {
                    sumOfFixedFees = sumOfFixedFees.add(preview.getFees().get(fee));
                } else {
                    sumOfPercentageFees = sumOfPercentageFees.add(preview.getFees().get(fee));
                }
            }
        }
        // Show a warning if there are fixed fees and if the amount is not enough to cover them
        if (sumOfFixedFees.signum() == 1) {
            final int scale = LocalSettings.MAX_PRECISION;
            final MathContext mc = new MathContext(scale);
            final BigDecimal sumOfPercentages = sumOfPercentageFees.divide(payment.getAmount(), mc);
            final BigDecimal minimalAmount = sumOfFixedFees.divide((BigDecimal.ONE.subtract(sumOfPercentages)),
                    mc);
            amount.comparable(minimalAmount, ">", new ValidationError("errors.greaterThan",
                    messageResolver.message("transactionFee.invalidChargeValue", minimalAmount)));
        } else if (preview.getFinalAmount().signum() == -1) {
            validator.general(new FinalAmountValidator());
        }

        // Custom fields
        validator.chained(new DelegatingValidator(new DelegatingValidator.DelegateSource() {
            @Override
            public Validator getValidator() {
                return paymentCustomFieldService.getValueValidator(payment.getTransferType());
            }
        }));
    }
    return validator;
}

From source file:net.sourceforge.fenixedu.domain.ExecutionCourse.java

public void setUnitCreditValue(BigDecimal unitCreditValue, String justification) {
    if (unitCreditValue != null && (unitCreditValue.compareTo(BigDecimal.ZERO) < 0
            || unitCreditValue.compareTo(BigDecimal.ONE) > 0)) {
        throw new DomainException("error.executionCourse.unitCreditValue.range");
    }//from ww  w  . java 2  s .  c  om
    if (unitCreditValue != null && unitCreditValue.compareTo(BigDecimal.ZERO) != 0 && getEffortRate() == null) {
        throw new DomainException("error.executionCourse.unitCreditValue.noEffortRate");
    }
    if (getEffortRate() != null && (unitCreditValue != null
            && unitCreditValue.compareTo(BigDecimal.valueOf(Math.min(getEffortRate().doubleValue(), 1.0))) < 0
            && StringUtils.isBlank(justification))) {
        throw new DomainException(
                "error.executionCourse.unitCreditValue.lower.effortRate.withoutJustification");
    }
    super.setUnitCreditValueNotes(justification);
    super.setUnitCreditValue(unitCreditValue);
}

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

/**
 * Riemann zeta function.// www.  ja  va  2s .  c om
 *
 * @param n The positive integer argument.
 * @return zeta(n)-1.
 */
static public double zeta1(final int n) {
    /* precomputed static table in double precision
     */
    final double[] zmin1 = { 0., 0., 6.449340668482264364724151666e-01, 2.020569031595942853997381615e-01,
            8.232323371113819151600369654e-02, 3.692775514336992633136548646e-02,
            1.734306198444913971451792979e-02, 8.349277381922826839797549850e-03,
            4.077356197944339378685238509e-03, 2.008392826082214417852769232e-03,
            9.945751278180853371459589003e-04, 4.941886041194645587022825265e-04,
            2.460865533080482986379980477e-04, 1.227133475784891467518365264e-04,
            6.124813505870482925854510514e-05, 3.058823630702049355172851064e-05,
            1.528225940865187173257148764e-05, 7.637197637899762273600293563e-06,
            3.817293264999839856461644622e-06, 1.908212716553938925656957795e-06,
            9.539620338727961131520386834e-07, 4.769329867878064631167196044e-07,
            2.384505027277329900036481868e-07, 1.192199259653110730677887189e-07,
            5.960818905125947961244020794e-08, 2.980350351465228018606370507e-08,
            1.490155482836504123465850663e-08, 7.450711789835429491981004171e-09,
            3.725334024788457054819204018e-09, 1.862659723513049006403909945e-09,
            9.313274324196681828717647350e-10, 4.656629065033784072989233251e-10,
            2.328311833676505492001455976e-10, 1.164155017270051977592973835e-10,
            5.820772087902700889243685989e-11, 2.910385044497099686929425228e-11,
            1.455192189104198423592963225e-11, 7.275959835057481014520869012e-12,
            3.637979547378651190237236356e-12, 1.818989650307065947584832101e-12,
            9.094947840263889282533118387e-13, 4.547473783042154026799112029e-13,
            2.273736845824652515226821578e-13, 1.136868407680227849349104838e-13,
            5.684341987627585609277182968e-14, 2.842170976889301855455073705e-14,
            1.421085482803160676983430714e-14, 7.105427395210852712877354480e-15,
            3.552713691337113673298469534e-15, 1.776356843579120327473349014e-15,
            8.881784210930815903096091386e-16, 4.440892103143813364197770940e-16,
            2.220446050798041983999320094e-16, 1.110223025141066133720544570e-16,
            5.551115124845481243723736590e-17, 2.775557562136124172581632454e-17,
            1.387778780972523276283909491e-17, 6.938893904544153697446085326e-18,
            3.469446952165922624744271496e-18, 1.734723476047576572048972970e-18,
            8.673617380119933728342055067e-19, 4.336808690020650487497023566e-19,
            2.168404344997219785013910168e-19, 1.084202172494241406301271117e-19,
            5.421010862456645410918700404e-20, 2.710505431223468831954621312e-20,
            1.355252715610116458148523400e-20, 6.776263578045189097995298742e-21,
            3.388131789020796818085703100e-21, 1.694065894509799165406492747e-21,
            8.470329472546998348246992609e-22, 4.235164736272833347862270483e-22,
            2.117582368136194731844209440e-22, 1.058791184068023385226500154e-22,
            5.293955920339870323813912303e-23, 2.646977960169852961134116684e-23,
            1.323488980084899080309451025e-23, 6.617444900424404067355245332e-24,
            3.308722450212171588946956384e-24, 1.654361225106075646229923677e-24,
            8.271806125530344403671105617e-25, 4.135903062765160926009382456e-25,
            2.067951531382576704395967919e-25, 1.033975765691287099328409559e-25,
            5.169878828456431320410133217e-26, 2.584939414228214268127761771e-26,
            1.292469707114106670038112612e-26, 6.462348535570531803438002161e-27,
            3.231174267785265386134814118e-27, 1.615587133892632521206011406e-27,
            8.077935669463162033158738186e-28, 4.038967834731580825622262813e-28,
            2.019483917365790349158762647e-28, 1.009741958682895153361925070e-28,
            5.048709793414475696084771173e-29, 2.524354896707237824467434194e-29,
            1.262177448353618904375399966e-29, 6.310887241768094495682609390e-30,
            3.155443620884047239109841220e-30, 1.577721810442023616644432780e-30,
            7.888609052210118073520537800e-31 };

    if (n <= 0) {
        throw new ProviderException("Unimplemented zeta at negative argument " + n);
    }

    if (n == 1) {
        throw new ArithmeticException("Pole at zeta(1) ");
    }

    if (n < zmin1.length) /* look it up if available */ {
        return zmin1[n];
    } else {
        /* Result is roughly 2^(-n), desired accuracy 18 digits. If zeta(n) is computed, the equivalent accuracy
         * in relative units is higher, because zeta is around 1.
         */
        double eps = 1.e-18 * Math.pow(2., (double) (-n));
        MathContext mc = new MathContext(err2prec(eps));

        return zeta(n, mc).subtract(BigDecimal.ONE).doubleValue();

    }
}