Example usage for java.math BigDecimal ROUND_DOWN

List of usage examples for java.math BigDecimal ROUND_DOWN

Introduction

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

Prototype

int ROUND_DOWN

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

Click Source Link

Document

Rounding mode to round towards zero.

Usage

From source file:org.meerkat.services.WebApp.java

/**
 * getAvailabilityIndicator/*from  w  w w . jav  a 2  s . c  o  m*/
 * @return    1 if last availability higher than availability average
 *          -1 if last avail. lower than avail. average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getAvailabilityIndicator() {
    double doubleAvailAverage = getAvailabilityAverage();
    BigDecimal bd = new BigDecimal(doubleAvailAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double availAverage = bd.doubleValue();

    // get the value of last event
    double lastAvailability = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxId = embDB.getMaxIDofApp(this.getName());
    try {
        ps = conn.prepareStatement("SELECT ID, AVAILABILITY " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.getName() + "' " + "AND ID = " + maxId);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastAvailability = rs.getDouble(2);
        }

        rs.close();
        ps.close();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastAvailability);
    bd1 = bd1.setScale(2, BigDecimal.ROUND_DOWN);
    lastAvailability = bd1.doubleValue();

    if (lastAvailability > availAverage) {
        return 1;
    } else if (lastAvailability < availAverage) {
        return -1;
    }

    return 0;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getLoadTimeIndicator//from   w  w  w.jav a2s .com
 * @return    1 if last load time higher than load time average
 *          -1 if last load time lower than load time average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getLoadTimeIndicator() {
    double doubleLoadTimeAverage = getAppLoadTimeAVG();
    BigDecimal bd = new BigDecimal(doubleLoadTimeAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double loadTimeAverage = bd.doubleValue();

    // get the value of last event
    double lastLoadTime = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxID = embDB.getMaxIDofApp(this.name);

    try {
        ps = conn.prepareStatement("SELECT ID, LOADTIME " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.name + "' " + "AND ID = " + maxID);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastLoadTime = rs.getDouble(2);
        }

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average load time from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastLoadTime);
    bd1 = bd1.setScale(3, BigDecimal.ROUND_DOWN);
    lastLoadTime = bd1.doubleValue();

    if (lastLoadTime > loadTimeAverage) {
        return 1;
    } else if (lastLoadTime < loadTimeAverage) {
        return -1;
    }

    return 0;
}

From source file:com.cisco.dvbu.ps.deploytool.dao.jdbcapi.RegressionPerfTestDAOImpl.java

private String executePerformanceTestWorkers() throws CompositeException {
    try {//from   w  ww . j a  v  a2s . c  o  m
        // Create all the connections
        Worker[] workers = new Worker[perfTestThreads];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker();
        }
        // Pause in between query executions
        Thread.sleep(perfTestSleepExec * 1000);

        // Start the clock
        long startTime = System.currentTimeMillis();
        endTime = startTime + perfTestDuration * 1000;

        // Start the workers
        for (int i = 0; i < workers.length; i++) {
            workers[i].start();
        }

        // Output the Header Rows
        String content = CommonUtils.lpad(HEADER, 7, padChar) + logDelim
                + CommonUtils.rpad("Threads=" + perfTestThreads, 12, padChar) + logDelim
                + CommonUtils.rpad("Duration (s)=" + perfTestDuration, 17, padChar) + logDelim
                + CommonUtils.rpad("Print Sleep (s)=" + perfTestSleepPrint, 19, padChar) + logDelim
                + CommonUtils.rpad("Exec Sleep (s)=" + perfTestSleepExec, 18, padChar) + logDelim + logDelim
                + logDelim + logDelim;

        RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, "");
        StringBuffer buf = new StringBuffer();
        buf.append(content + "\n");

        content = CommonUtils.lpad(HEADER, 8, padChar) + logDelim + CommonUtils.rpad("Execs", 12, padChar)
                + logDelim + CommonUtils.rpad("Execs/sec", 12, padChar) + logDelim
                + CommonUtils.rpad("Rows/exec", 12, padChar) + logDelim
                + CommonUtils.rpad("Latency (ms)", 13, padChar) + logDelim
                + CommonUtils.rpad("1st row (ms)", 13, padChar) + logDelim
                + CommonUtils.rpad("Duration (ms)", 14, padChar) + logDelim + logDelim;

        RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, "");
        buf.append(content + "\n");

        // Initialize the totals before each query execution.
        numStatExecs.set(0);
        execsTotal = 0;
        tpsTotal = new BigDecimal(0);
        rptTotal = new BigDecimal(0);
        latTotal = new BigDecimal(0);
        frTotal = new BigDecimal(0);
        durTotal = new BigDecimal(0);

        /* Safeguard: determine the number of loops by taking the "total duration" divided by the "print stat sleep interval"
         *   This is important because sometimes the timing is off when the end time is calculated and when worker threads are 
         *   still running.  The issue is pointed out below (-->) when there is an extra line printed that throws off the stats.
         *   
         *    HEADER|Threads=1   |Duration (s)=10  |Print Sleep (s)=5  |Exec Sleep (s)=0  ||||
         *    HEADER|Execs       |Execs/sec   |Rows/exec   |Latency (ms) |1st row (ms) |Duration (ms) ||
         *    DETAIL|4780        |957.91      |1.00        |1.04         |1.03         |4990.00             ||
         *    DETAIL|5146        |1027.96     |1.00        |0.97         |0.96         |5006.00             ||
         * -->DETAIL|11          |2.19        |1.00        |0.90         |0.90         |5018.00             ||
         *    TOTALS|3312.33     |662.68      |1.00        |0.97         |0.96         |5004.66             ||
         */
        int totalExecLoops = perfTestDuration / perfTestSleepPrint;

        // Print stats periodically
        errorFound = false;
        int loopCounter = 0;
        while (System.currentTimeMillis() < endTime && !errorFound && loopCounter < totalExecLoops) {
            Thread.sleep(perfTestSleepPrint * 1000);
            content = printStats(startTime);
            if (content != null)
                buf.append(content);

            // Reset print stat counters              
            numExecs.set(0);
            numLatency.set(0);
            firstRowLatency.set(0);
            numRows.set(0);
            startTime = System.currentTimeMillis();
            loopCounter++;
        }

        // Wait for the workers to finish
        for (int i = 0; i < workers.length; i++) {
            workers[i].join();
        }

        // Print stats
        /*
         * This is @deprecated as it was determined that the last stat line was inconsistent and throwing off the numbers
        content = printStats(startTime);
        if (content != null)
           buf.append(content);
        */

        // Calculate the Total Average Stats for each run and output as a TOTALS line
        if (numStatExecs.get() > 0) {
            // Calculate total average executions
            BigDecimal execAvg = new BigDecimal(execsTotal);
            execAvg = execAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            execAvg = execAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average execs/sec or tps
            BigDecimal tpsAvg = tpsTotal;
            tpsAvg = tpsAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            tpsAvg = tpsAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average Rows per Execution
            BigDecimal rptAvg = rptTotal;
            rptAvg = rptAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            rptAvg = rptAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average Latency
            BigDecimal latAvg = latTotal;
            latAvg = latAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            latAvg = latAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average First Row Latency
            BigDecimal frAvg = frTotal;
            frAvg = frAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            frAvg = frAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average Duration
            BigDecimal durAvg = durTotal;
            durAvg = durAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            durAvg = durAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Print out the summary Totals line
            content = CommonUtils.lpad(TOTALS, 8, padChar) + logDelim
                    + CommonUtils.rpad("" + execAvg, 12, padChar) + logDelim
                    + CommonUtils.rpad("" + tpsAvg, 12, padChar) + logDelim
                    + CommonUtils.rpad("" + rptAvg, 12, padChar) + logDelim
                    + CommonUtils.rpad("" + latAvg, 13, padChar) + logDelim
                    + CommonUtils.rpad("" + frAvg, 13, padChar) + logDelim
                    + CommonUtils.rpad("" + durAvg, 20, padChar) + logDelim + logDelim;

            RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, "");
            buf.append(content + "\n");
        }

        return buf.toString();
    } catch (Exception e) {
        throw new ApplicationException(e);
    }
}

From source file:com.cisco.dvbu.ps.deploytool.dao.jdbcapi.RegressionPerfTestDAOImpl.java

public static String printStats(long startTime) {
    String content = null;/* w  w w  .j  a v a  2  s .c o m*/
    long duration = System.currentTimeMillis() - startTime;
    if (numExecs.get() == 0 || startTime <= 0 || duration <= 0) {
        return content;
    }
    // Increment the number of print stats executions which is used for averaging totals
    numStatExecs.addAndGet(1);

    // Calculate total number of executions
    execsTotal = execsTotal + numExecs.get();

    // Calculate Executions per Second or TPS - transactions per second
    double tps = numExecs.get() * 1000.0 / duration;
    BigDecimal tpsBd = new BigDecimal(tps);
    tpsBd = tpsBd.setScale(2, BigDecimal.ROUND_DOWN);
    tpsTotal = tpsTotal.add(tpsBd);

    // Calculate Rows per Execution
    double rpt = ((double) numRows.get()) / numExecs.get();
    BigDecimal rptBd = new BigDecimal(rpt);
    rptBd = rptBd.setScale(2, BigDecimal.ROUND_DOWN);
    rptTotal = rptTotal.add(rptBd);

    // Calculate Latency
    double latency = ((double) numLatency.get()) / numExecs.get();
    BigDecimal latBd = new BigDecimal(latency);
    latBd = latBd.setScale(2, BigDecimal.ROUND_DOWN);
    latTotal = latTotal.add(latBd);

    // Calculate First Row Latency
    double firstRow = ((double) firstRowLatency.get()) / numExecs.get();
    BigDecimal frBd = new BigDecimal(firstRow);
    frBd = frBd.setScale(2, BigDecimal.ROUND_DOWN);
    frTotal = frTotal.add(frBd);

    // Calculate Duration
    BigDecimal durBd = new BigDecimal(duration);
    durBd = durBd.setScale(2, BigDecimal.ROUND_DOWN);
    durTotal = durTotal.add(durBd);

    content = CommonUtils.lpad(DETAIL, 8, padChar) + logDelim
            + CommonUtils.rpad("" + numExecs.get(), 12, padChar) + logDelim
            + CommonUtils.rpad("" + tpsBd, 12, padChar) + logDelim + CommonUtils.rpad("" + rptBd, 12, padChar)
            + logDelim + CommonUtils.rpad("" + latBd, 13, padChar) + logDelim
            + CommonUtils.rpad("" + frBd, 13, padChar) + logDelim + CommonUtils.rpad("" + durBd, 20, padChar)
            + logDelim + logDelim;
    RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, "");
    content += "\n";
    /*
     * Execs       Execs/sec   Rows/exec   Latency (ms) 1st row (ms) Duration (ms)
    *   1191        237.86      9.00        4.19         4.19        5000 
    *   1387        276.90      9.00        3.61         3.61        5003
     */
    return content;
}

From source file:com.dp2345.Setting.java

/**
 * /*from www.j  a va 2 s. c  o m*/
 * 
 * @param amount
 *            
 * @return 
 */
public BigDecimal setScale(BigDecimal amount) {
    if (amount == null) {
        return null;
    }
    int roundingMode;
    if (getPriceRoundType() == RoundType.roundUp) {
        roundingMode = BigDecimal.ROUND_UP;
    } else if (getPriceRoundType() == RoundType.roundDown) {
        roundingMode = BigDecimal.ROUND_DOWN;
    } else {
        roundingMode = BigDecimal.ROUND_HALF_UP;
    }
    return amount.setScale(getPriceScale(), roundingMode);
}

From source file:org.apache.hadoop.hbase.io.hfile.slab.SlabCache.java

/**
 * A way of allocating the desired amount of Slabs of each particular size.
 *
 * This reads two lists from conf, hbase.offheap.slab.proportions and
 * hbase.offheap.slab.sizes./*from ww  w  .j  ava  2  s.c  om*/
 *
 * The first list is the percentage of our total space we allocate to the
 * slabs.
 *
 * The second list is blocksize of the slabs in bytes. (E.g. the slab holds
 * blocks of this size).
 *
 * @param conf Configuration file.
 */
public void addSlabByConf(Configuration conf) {
    // Proportions we allocate to each slab of the total size.
    String[] porportions = conf.getStrings(SLAB_CACHE_PROPORTIONS_KEY, "0.80", "0.20");
    String[] sizes = conf.getStrings(SLAB_CACHE_SIZES_KEY, Long.valueOf(avgBlockSize * 11 / 10).toString(),
            Long.valueOf(avgBlockSize * 21 / 10).toString());

    if (porportions.length != sizes.length) {
        throw new IllegalArgumentException("SlabCache conf not "
                + "initialized, error in configuration. hbase.offheap.slab.proportions specifies "
                + porportions.length + " slabs while hbase.offheap.slab.sizes specifies " + sizes.length
                + " slabs " + "offheapslabporportions and offheapslabsizes");
    }
    /*
     * We use BigDecimals instead of floats because float rounding is annoying
     */

    BigDecimal[] parsedProportions = stringArrayToBigDecimalArray(porportions);
    BigDecimal[] parsedSizes = stringArrayToBigDecimalArray(sizes);

    BigDecimal sumProportions = new BigDecimal(0);
    for (BigDecimal b : parsedProportions) {
        /* Make sure all proportions are greater than 0 */
        Preconditions.checkArgument(b.compareTo(BigDecimal.ZERO) == 1,
                "Proportions in hbase.offheap.slab.proportions must be greater than 0!");
        sumProportions = sumProportions.add(b);
    }

    /* If the sum is greater than 1 */
    Preconditions.checkArgument(sumProportions.compareTo(BigDecimal.ONE) != 1,
            "Sum of all proportions in hbase.offheap.slab.proportions must be less than 1");

    /* If the sum of all proportions is less than 0.99 */
    if (sumProportions.compareTo(new BigDecimal("0.99")) == -1) {
        LOG.warn("Sum of hbase.offheap.slab.proportions is less than 0.99! Memory is being wasted");
    }
    for (int i = 0; i < parsedProportions.length; i++) {
        int blockSize = parsedSizes[i].intValue();
        int numBlocks = new BigDecimal(this.size).multiply(parsedProportions[i])
                .divide(parsedSizes[i], BigDecimal.ROUND_DOWN).intValue();
        addSlab(blockSize, numBlocks);
    }
}

From source file:org.apache.hama.examples.util.VectorWritableMatrixGen.java

public static double[][] createRandomMatrix(int rows, int columns, Random rand, double rangeMin,
        double rangeMax, int precision) {

    LOG.debug("createRandomMatrix rows: " + rows + " cols: " + columns);

    final double[][] matrix = new double[rows][columns];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            double randomValue = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();

            matrix[i][j] = new BigDecimal(randomValue).setScale(precision, BigDecimal.ROUND_DOWN).doubleValue();
        }/*from www .  jav  a 2s.  c  o  m*/
    }
    return matrix;
}

From source file:org.apache.hama.pipes.TestPipes.java

static BigDecimal writeSummationInputFile(FileSystem fs, Path dir) throws IOException {
    DataOutputStream out = fs.create(new Path(dir, "part0"));
    Random rand = new Random();
    double rangeMin = 0;
    double rangeMax = 100;
    BigDecimal sum = new BigDecimal(0);
    // loop between 50 and 149 times
    for (int i = 0; i < rand.nextInt(100) + 50; i++) {
        // generate key value pair inputs
        double randomValue = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();
        String truncatedValue = new BigDecimal(randomValue).setScale(DOUBLE_PRECISION, BigDecimal.ROUND_DOWN)
                .toString();/*ww w .  j a va 2 s.  c  o m*/

        String line = "key" + (i + 1) + "\t" + truncatedValue + "\n";
        out.writeBytes(line);

        sum = sum.add(new BigDecimal(truncatedValue));
    }
    out.close();
    return sum;
}

From source file:org.apache.hama.pipes.TestPipes.java

static double[][] createRandomMatrix(int rows, int columns, Random rand) {
    final double[][] matrix = new double[rows][columns];
    double rangeMin = 0;
    double rangeMax = 100;

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            double randomValue = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();
            matrix[i][j] = new BigDecimal(randomValue).setScale(DOUBLE_PRECISION, BigDecimal.ROUND_DOWN)
                    .doubleValue();// ww  w .  j av a 2  s. c  o m
        }
    }
    return matrix;
}

From source file:org.egov.infra.gis.service.GeoLocationService.java

private static String getStyleColorName(BigDecimal wardWiseNos, BigDecimal wardDataMinAmount,
        Integer totalNoOfColors, BigDecimal rangeSize) {

    return "#color" + (BigDecimal.valueOf(totalNoOfColors)
            .subtract((wardWiseNos.subtract(wardDataMinAmount).subtract(BigDecimal.ONE)).divide(rangeSize, 0,
                    BigDecimal.ROUND_DOWN)));

}