Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:adalid.commons.util.ObjUtils.java

public static Integer compare(Object x, Object y) {
    if (x == null || y == null) {
        return null;
    }// www.  j a v a  2 s .c  om
    if (x instanceof Boolean && y instanceof Boolean) {
        Boolean bx = (Boolean) x;
        Boolean by = (Boolean) y;
        return bx.compareTo(by);
    }
    if (x instanceof String && y instanceof String) {
        String sx = (String) x;
        String sy = (String) y;
        return sx.compareTo(sy);
    }
    if (x instanceof Number && y instanceof Number) {
        BigDecimal nx = NumUtils.numberToBigDecimal(x);
        BigDecimal ny = NumUtils.numberToBigDecimal(y);
        return nx.compareTo(ny);
    }
    if (x instanceof java.util.Date && y instanceof java.util.Date) {
        java.util.Date dx = (java.util.Date) x;
        java.util.Date dy = (java.util.Date) y;
        return dx.compareTo(dy);
    }
    if (x instanceof String || y instanceof String) {
        String sx = toString(x);
        String sy = toString(y);
        if (sx != null && sy != null) {
            return sx.compareTo(sy);
        }
    }
    return null;
}

From source file:org.apache.tajo.master.Repartitioner.java

public static QueryUnit[] createRangePartitionedTasks(SubQuery subQuery, SubQuery childSubQuery, int maxNum)
        throws InternalException {
    ExecutionBlock execBlock = subQuery.getBlock();
    TableStat stat = childSubQuery.getTableStat();
    if (stat.getNumRows() == 0) {
        return new QueryUnit[0];
    }/*from   w w  w.  j a v  a  2 s  .  c o  m*/

    ScanNode scan = execBlock.getScanNodes()[0];
    Path tablePath;
    tablePath = subQuery.getContext().getStorageManager().getTablePath(scan.getTableId());

    StoreTableNode store = (StoreTableNode) childSubQuery.getBlock().getPlan();
    SortNode sort = (SortNode) store.getSubNode();
    SortSpec[] sortSpecs = sort.getSortKeys();
    Schema sortSchema = PlannerUtil.sortSpecsToSchema(sort.getSortKeys());

    // calculate the number of maximum query ranges
    TupleRange mergedRange = TupleUtil.columnStatToRange(sort.getOutSchema(), sortSchema,
            stat.getColumnStats());
    RangePartitionAlgorithm partitioner = new UniformRangePartition(sortSchema, mergedRange);
    BigDecimal card = partitioner.getTotalCardinality();

    // if the number of the range cardinality is less than the desired number of tasks,
    // we set the the number of tasks to the number of range cardinality.
    int determinedTaskNum;
    if (card.compareTo(new BigDecimal(maxNum)) < 0) {
        LOG.info("The range cardinality (" + card + ") is less then the desired number of tasks (" + maxNum
                + ")");
        determinedTaskNum = card.intValue();
    } else {
        determinedTaskNum = maxNum;
    }

    LOG.info("Try to divide " + mergedRange + " into " + determinedTaskNum + " sub ranges (total units: "
            + determinedTaskNum + ")");
    TupleRange[] ranges = partitioner.partition(determinedTaskNum);

    Fragment dummyFragment = new Fragment(scan.getTableId(), tablePath,
            CatalogUtil.newTableMeta(scan.getInSchema(), StoreType.CSV), 0, 0, null);

    List<String> basicFetchURIs = new ArrayList<String>();

    SubQuery child = childSubQuery.getContext().getSubQuery(subQuery.getBlock().getChildBlock(scan).getId());
    for (QueryUnit qu : child.getQueryUnits()) {
        for (IntermediateEntry p : qu.getIntermediateData()) {
            String uri = createBasicFetchUri(p.getPullHost(), p.getPullPort(), childSubQuery.getId(), p.taskId,
                    p.attemptId);
            basicFetchURIs.add(uri);
        }
    }

    boolean ascendingFirstKey = sortSpecs[0].isAscending();
    SortedMap<TupleRange, Set<URI>> map;
    if (ascendingFirstKey) {
        map = new TreeMap<TupleRange, Set<URI>>();
    } else {
        map = new TreeMap<TupleRange, Set<URI>>(new TupleRange.DescendingTupleRangeComparator());
    }

    Set<URI> uris;
    try {
        for (int i = 0; i < ranges.length; i++) {
            uris = new HashSet<URI>();
            for (String uri : basicFetchURIs) {
                String rangeParam = TupleUtil.rangeToQuery(sortSchema, ranges[i], ascendingFirstKey,
                        ascendingFirstKey ? i == (ranges.length - 1) : i == 0);
                URI finalUri = URI.create(uri + "&" + rangeParam);
                uris.add(finalUri);
            }
            map.put(ranges[i], uris);
        }

    } catch (UnsupportedEncodingException e) {
        LOG.error(e);
    }

    QueryUnit[] tasks = createEmptyNonLeafTasks(subQuery, determinedTaskNum, dummyFragment);
    assignPartitionByRoundRobin(map, scan.getTableId(), tasks);
    return tasks;
}

From source file:NumberInRange.java

public static boolean isInRange(Number number, BigDecimal min, BigDecimal max) {
    try {/*  w ww . ja  va2s  .c  o  m*/
        BigDecimal bigDecimal = null;
        if (number instanceof Byte || number instanceof Short || number instanceof Integer
                || number instanceof Long) {
            bigDecimal = new BigDecimal(number.longValue());
        } else if (number instanceof Float || number instanceof Double) {
            bigDecimal = new BigDecimal(number.doubleValue());
        } else if (number instanceof BigInteger) {
            bigDecimal = new BigDecimal((BigInteger) number);
        } else if (number instanceof BigDecimal) {
            bigDecimal = (BigDecimal) number;
        } else {
            bigDecimal = new BigDecimal(number.doubleValue());
        }
        return max.compareTo(bigDecimal) >= 0 && min.compareTo(bigDecimal) <= 0;
    } catch (NumberFormatException e) {
        return false;
    }
}

From source file:com.espertech.esper.regression.expr.TestFilterExpressionsOptimizable.java

public static boolean myCustomBigDecimalEquals(final BigDecimal first, final BigDecimal second) {
    return first.compareTo(second) == 0;
}

From source file:Main.java

public static BigDecimal log10(BigDecimal b) {
    final int NUM_OF_DIGITS = SCALE + 2;
    // need to add one to get the right number of dp
    //  and then add one again to get the next number
    //  so I can round it correctly.

    MathContext mc = new MathContext(NUM_OF_DIGITS, RoundingMode.HALF_EVEN);
    //special conditions:
    // log(-x) -> exception
    // log(1) == 0 exactly;
    // log of a number lessthan one = -log(1/x)
    if (b.signum() <= 0) {
        throw new ArithmeticException("log of a negative number! (or zero)");
    } else if (b.compareTo(BigDecimal.ONE) == 0) {
        return BigDecimal.ZERO;
    } else if (b.compareTo(BigDecimal.ONE) < 0) {
        return (log10((BigDecimal.ONE).divide(b, mc))).negate();
    }/*from   w  w w . ja  v  a2s .co  m*/

    StringBuilder sb = new StringBuilder();
    //number of digits on the left of the decimal point
    int leftDigits = b.precision() - b.scale();

    //so, the first digits of the log10 are:
    sb.append(leftDigits - 1).append(".");

    //this is the algorithm outlined in the webpage
    int n = 0;
    while (n < NUM_OF_DIGITS) {
        b = (b.movePointLeft(leftDigits - 1)).pow(10, mc);
        leftDigits = b.precision() - b.scale();
        sb.append(leftDigits - 1);
        n++;
    }

    BigDecimal ans = new BigDecimal(sb.toString());

    //Round the number to the correct number of decimal places.
    ans = ans.round(new MathContext(ans.precision() - ans.scale() + SCALE, RoundingMode.HALF_EVEN));
    return ans;
}

From source file:Main.java

public static BigDecimal log10(BigDecimal b) {
    final int NUM_OF_DIGITS = SCALE + 2;
    // need to add one to get the right number of dp
    // and then add one again to get the next number
    // so I can round it correctly.

    MathContext mc = new MathContext(NUM_OF_DIGITS, RoundingMode.HALF_EVEN);
    // special conditions:
    // log(-x) -> exception
    // log(1) == 0 exactly;
    // log of a number lessthan one = -log(1/x)
    if (b.signum() <= 0) {
        throw new ArithmeticException("log of a negative number! (or zero)");
    } else if (b.compareTo(BigDecimal.ONE) == 0) {
        return BigDecimal.ZERO;
    } else if (b.compareTo(BigDecimal.ONE) < 0) {
        return (log10((BigDecimal.ONE).divide(b, mc))).negate();
    }//  w  w  w  .jav  a  2  s. c o  m

    StringBuilder sb = new StringBuilder();
    // number of digits on the left of the decimal point
    int leftDigits = b.precision() - b.scale();

    // so, the first digits of the log10 are:
    sb.append(leftDigits - 1).append(".");

    // this is the algorithm outlined in the webpage
    int n = 0;
    while (n < NUM_OF_DIGITS) {
        b = (b.movePointLeft(leftDigits - 1)).pow(10, mc);
        leftDigits = b.precision() - b.scale();
        sb.append(leftDigits - 1);
        n++;
    }

    BigDecimal ans = new BigDecimal(sb.toString());

    // Round the number to the correct number of decimal places.
    ans = ans.round(new MathContext(ans.precision() - ans.scale() + SCALE, RoundingMode.HALF_EVEN));
    return ans;
}

From source file:com.bloatit.model.Payment.java

public static BankTransaction doPayment(final Actor<?> targetActor, final BigDecimal amount)
        throws UnauthorizedOperationException {
    if (!AuthToken.isAuthenticated()) {
        throw new UnauthorizedOperationException(SpecialCode.AUTHENTICATION_NEEDED);
    }/*  w ww  .  j ava2  s.  c  om*/
    if (!targetActor.equals(AuthToken.getMember()) && !targetActor.equals(AuthToken.getAsTeam())) {

    }

    final BigDecimal amountToPay = BankTransaction.computateAmountToPay(amount);

    if (amountToPay.scale() > 2) {
        throw new BadProgrammerException("The amount to pay cannot have more than 2 digit after the '.'.");
    }
    if (amount.scale() > 2) {
        throw new BadProgrammerException("The amount cannot have more than 2 digit after the '.'.");
    }
    if (amount.compareTo(amountToPay) > 0) {
        throw new BadProgrammerException("The amount to pay must be superior to the amount '.'.");
    }

    final String orderReference = createOrderRef(targetActor);

    final BankTransaction bankTransaction = new BankTransaction(targetActor, //
            amount, //
            amountToPay, //
            orderReference);
    bankTransaction.setAuthorized();

    return bankTransaction;
}

From source file:Main.java

/**
 * Compute e^x to a given scale./* w ww  .j  av  a 2  s. c o m*/
 * Break x into its whole and fraction parts and
 * compute (e^(1 + fraction/whole))^whole using Taylor's formula.
 * @param x the value of x
 * @param scale the desired scale of the result
 * @return the result value
 */
public static BigDecimal exp(BigDecimal x, int scale) {
    // e^0 = 1
    if (x.signum() == 0) {
        return BigDecimal.valueOf(1);
    }

    // If x is negative, return 1/(e^-x).
    else if (x.signum() == -1) {
        return BigDecimal.valueOf(1).divide(exp(x.negate(), scale), scale, BigDecimal.ROUND_HALF_EVEN);
    }

    // Compute the whole part of x.
    BigDecimal xWhole = x.setScale(0, BigDecimal.ROUND_DOWN);

    // If there isn't a whole part, compute and return e^x.
    if (xWhole.signum() == 0)
        return expTaylor(x, scale);

    // Compute the fraction part of x.
    BigDecimal xFraction = x.subtract(xWhole);

    // z = 1 + fraction/whole
    BigDecimal z = BigDecimal.valueOf(1).add(xFraction.divide(xWhole, scale, BigDecimal.ROUND_HALF_EVEN));

    // t = e^z
    BigDecimal t = expTaylor(z, scale);

    BigDecimal maxLong = BigDecimal.valueOf(Long.MAX_VALUE);
    BigDecimal result = BigDecimal.valueOf(1);

    // Compute and return t^whole using intPower().
    // If whole > Long.MAX_VALUE, then first compute products
    // of e^Long.MAX_VALUE.
    while (xWhole.compareTo(maxLong) >= 0) {
        result = result.multiply(intPower(t, Long.MAX_VALUE, scale)).setScale(scale,
                BigDecimal.ROUND_HALF_EVEN);
        xWhole = xWhole.subtract(maxLong);

        Thread.yield();
    }
    return result.multiply(intPower(t, xWhole.longValue(), scale)).setScale(scale, BigDecimal.ROUND_HALF_EVEN);
}

From source file:org.apache.phoenix.util.TestUtil.java

public static void assertRoundEquals(BigDecimal bd1, BigDecimal bd2) {
    bd1 = bd1.round(PDataType.DEFAULT_MATH_CONTEXT);
    bd2 = bd2.round(PDataType.DEFAULT_MATH_CONTEXT);
    if (bd1.compareTo(bd2) != 0) {
        fail("expected:<" + bd1 + "> but was:<" + bd2 + ">");
    }//from   w w w .j  a v a2 s.c o m
}

From source file:org.apache.fineract.portfolio.loanaccount.domain.LoanCharge.java

private static boolean isGreaterThanZero(final BigDecimal value) {
    return value.compareTo(BigDecimal.ZERO) == 1;
}