Example usage for java.math BigDecimal ROUND_HALF_EVEN

List of usage examples for java.math BigDecimal ROUND_HALF_EVEN

Introduction

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

Prototype

int ROUND_HALF_EVEN

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

Click Source Link

Document

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

Usage

From source file:Main.java

/**
 * Compute the integral root of x to a given scale, x >= 0.
 * Use Newton's algorithm./*w  w  w .  j a  va2s  .  c  o  m*/
 * @param x the value of x
 * @param index the integral root value
 * @param scale the desired scale of the result
 * @return the result value
 */
public static BigDecimal intRoot(BigDecimal x, long index, int scale) {
    // Check that x >= 0.
    if (x.signum() < 0) {
        throw new IllegalArgumentException("x < 0");
    }

    int sp1 = scale + 1;
    BigDecimal n = x;
    BigDecimal i = BigDecimal.valueOf(index);
    BigDecimal im1 = BigDecimal.valueOf(index - 1);
    BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1);
    BigDecimal xPrev;

    // The initial approximation is x/index.
    x = x.divide(i, scale, BigDecimal.ROUND_HALF_EVEN);

    // Loop until the approximations converge
    // (two successive approximations are equal after rounding).
    do {
        // x^(index-1)
        BigDecimal xToIm1 = intPower(x, index - 1, sp1);

        // x^index
        BigDecimal xToI = x.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // n + (index-1)*(x^index)
        BigDecimal numerator = n.add(im1.multiply(xToI)).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // (index*(x^(index-1))
        BigDecimal denominator = i.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // x = (n + (index-1)*(x^index)) / (index*(x^(index-1)))
        xPrev = x;
        x = numerator.divide(denominator, sp1, BigDecimal.ROUND_DOWN);

        Thread.yield();
    } while (x.subtract(xPrev).abs().compareTo(tolerance) > 0);

    return x;
}

From source file:ustc.sse.controller.DataMiningController.java

/**
 * //  w ww.  ja v  a 2  s .c o m
 * @param request
 * @param response
 * @return
 * @throws UnsupportedEncodingException
 */
@RequestMapping("autoDocument")
public String autoDocument(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    TrainSampleDataManager.process();
    String article = new String((request.getParameter("article")).getBytes("ISO-8859-1"), "UTF-8");
    //"????????29???????????29??????????";
    //String s="????????????Foursquare?????";
    //String s="???????75%80????";
    //String s=" ????????CEOCEO????";
    //String s="???44621? ?????446?????3113119.1862%????20062007???????????????(?)";
    //String s="?Uber2.58????Uber???";
    //String s="? ??";
    Set<String> words = ChineseTokenizer.segStr(article).keySet();

    Map<String, BigDecimal> resultMap = MultinomialModelNaiveBayes
            .classifyResult(DefaultStopWordsHandler.dropStopWords(words));
    Set<String> set = resultMap.keySet();

    docClass.put("C000007", "");
    docClass.put("C000008", "?");
    docClass.put("C000010", "IT");
    docClass.put("C000013", "?");
    docClass.put("C000014", "");
    docClass.put("C000016", "");
    docClass.put("C000020", "");
    docClass.put("C000022", "?");
    docClass.put("C000023", "");
    docClass.put("C000024", "");

    List<Classifer> classifers = new LinkedList<Classifer>();
    BigDecimal total = new BigDecimal(0);
    BigDecimal probability = new BigDecimal(0);
    for (String str : set) {
        probability = resultMap.get(str);
        total = total.add(probability);
        log.info("classifer:" + str + "     probability:" + probability);
        Classifer classifer = new Classifer(docClass.get(str), probability);
        classifers.add(classifer);
    }
    //
    for (Classifer classifer : classifers) {
        classifer.setProbability((classifer.getProbability()).divide(total, 2, BigDecimal.ROUND_HALF_EVEN));
    }

    request.setAttribute("classifers", classifers);

    String classifyName = docClass.get(MultinomialModelNaiveBayes.getClassifyResultName());
    request.setAttribute("classifyName", classifyName);
    log.info("The final result:" + classifyName);
    return "autoDocument";
}

From source file:ch.algotrader.service.ib.IBNativeHistoricalDataServiceImpl.java

@Override
public synchronized List<Bar> getHistoricalBars(long securityId, Date endDate, int timePeriodLength,
        TimePeriod timePeriod, Duration barSize, MarketDataEventType marketDataEventType,
        Map<String, String> properties) {

    Validate.notNull(endDate, "End date is null");
    Validate.notNull(timePeriod, "Time period is null");
    Validate.notNull(barSize, "Bar size is null");
    Validate.notNull(marketDataEventType, "Bar type is null");

    Security security = this.securityDao.get(securityId);
    if (security == null) {
        throw new ServiceException("security was not found: " + securityId);
    }//from  w ww  .ja v a2s.  c  o  m

    int scale = security.getSecurityFamily().getScale(Broker.IB.name());
    Contract contract = IBUtil.getContract(security);
    int requestId = (int) this.requestIdGenerator.generateId();
    String dateString = dateTimeFormat.format(DateTimeLegacy.toLocalDateTime(endDate));

    String durationString = timePeriodLength + " ";
    switch (timePeriod) {
    case SEC:
        durationString += "S";
        break;
    case DAY:
        durationString += "D";
        break;
    case WEEK:
        durationString += "W";
        break;
    case MONTH:
        durationString += "M";
        break;
    case YEAR:
        durationString += "Y";
        break;
    default:
        throw new ServiceException("timePeriod is not allowed " + timePeriod);
    }

    String[] barSizeName = barSize.name().split("_");

    String barSizeString = barSizeName[1] + " ";
    switch (barSizeName[0]) {
    case "SEC":
        barSizeString += "sec";
        break;
    case "MIN":
        barSizeString += "min";
        break;
    case "HOUR":
        barSizeString += "hour";
        break;
    case "DAY":
        barSizeString += "day";
        break;
    default:
        throw new ServiceException("barSize is not allowed " + barSize);
    }

    if (Integer.parseInt(barSizeName[1]) > 1) {
        barSizeString += "s";
    }

    String marketDataEventTypeString;
    switch (marketDataEventType) {
    case TRADES:
        marketDataEventTypeString = "TRADES";
        break;
    case MIDPOINT:
        marketDataEventTypeString = "MIDPOINT";
        break;
    case BID:
        marketDataEventTypeString = "BID";
        break;
    case ASK:
        marketDataEventTypeString = "ASK";
        break;
    case BID_ASK:
        marketDataEventTypeString = "BID_ASK";
        break;
    default:
        throw new ServiceException("unsupported marketDataEventType " + marketDataEventType);
    }

    // avoid pacing violations
    long waitMillis = (this.lastTimeStamp.get() + pacingMillis) - System.currentTimeMillis();
    if (waitMillis > 0) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("waiting {} seconds until next historical data request",
                    new BigDecimal(((double) waitMillis) / 1000).setScale(2, BigDecimal.ROUND_HALF_EVEN));
        }
        try {
            Thread.sleep(waitMillis);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            throw new ServiceException(ex);
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "Request historic data; request id = {}; security id = {}; conId = {}; date = {}; duration = {}; bar size = {}",
                requestId, securityId, contract.m_conId, dateString, durationString, barSizeString);
    }

    PromiseImpl<List<Bar>> promise = new PromiseImpl<>(null);
    this.pendingRequests.addHistoricDataRequest(requestId, promise);
    this.iBSession.reqHistoricalData(requestId, contract, dateString, durationString, barSizeString,
            marketDataEventTypeString, this.iBConfig.useRTH() ? 1 : 0, 1, Collections.<TagValue>emptyList());
    List<Bar> bars = getBarsBlocking(promise);

    this.lastTimeStamp.set(System.currentTimeMillis());

    // set & update fields
    for (Bar bar : bars) {
        bar.setSecurity(security);
        bar.setFeedType(FeedType.IB.name());
        bar.getOpen().setScale(scale, RoundingMode.HALF_UP);
        bar.getHigh().setScale(scale, RoundingMode.HALF_UP);
        bar.getLow().setScale(scale, RoundingMode.HALF_UP);
        bar.getClose().setScale(scale, RoundingMode.HALF_UP);
        bar.getVwap().setScale(scale, RoundingMode.HALF_UP);
        bar.setBarSize(barSize);
    }
    return bars;
}

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static BigDecimal getBigDecimalForPriceTag(final Double amount) {
    if (amount == null) {
        return null;
    }// ww w .j av  a2  s. co  m
    return new BigDecimal(amount).setScale(PRICE_NUMBER_OF_DECIMALS, BigDecimal.ROUND_HALF_EVEN);
}

From source file:com.graphaware.neo4j.graphgen.faker.FakerService.java

/**
 * Returns a random double/*from w  w  w.j a va2 s.com*/
 *
 * @param maxNumberOfDecimals maximum number of places
 * @param min minimum value
 * @param max maximum value
 */

public double randomDouble(int maxNumberOfDecimals, int min, int max) {
    double value = min + (max - min) * random.nextDouble();

    return new BigDecimal(value).setScale(maxNumberOfDecimals, BigDecimal.ROUND_HALF_EVEN).doubleValue();
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Returns the push listener load factor computed as completedTaskCount/runningTime
 * in minutes (that is number of completed tasks in a minute)
 * @return the push listener load factor computed as completedTaskCount/runningTime
 *///  www.  j  av  a 2  s .  c om
public double getLoadFactor() {

    double runningTime = ((double) System.currentTimeMillis() - startingTime) / 60000; // in minutes

    if (runningTime == 0) {
        return 0;
    }

    long completedTask = getCompletedTaskCount();

    if (completedTask == 0) {
        return 0;
    }

    double loadFactor = (double) completedTask / runningTime;

    BigDecimal bd = new BigDecimal(loadFactor);
    bd = bd.setScale(1, BigDecimal.ROUND_HALF_EVEN);

    return bd.doubleValue();
}

From source file:op.tools.SYSTools.java

public static String roundScale2(BigDecimal bd) {
    return bd.setScale(2, BigDecimal.ROUND_HALF_EVEN).toPlainString();
}

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static BigDecimal getBigDecimalForPercentageTag(Double amount) {
    if (amount == null) {
        return null;
    }/*  w ww  . ja  v a2s.  co  m*/
    return new BigDecimal(amount).setScale(PERCENTAGE_NUMBER_OF_DECIMALS, BigDecimal.ROUND_HALF_EVEN);
}

From source file:org.libreplan.business.workingday.EffortDuration.java

/**
 * <p>/* w  ww  .ja v a2  s.c  om*/
 *     Divides this duration by other (using total seconds) returning the quotient as BigDecimal.
 * </p>
 *
 * @param other
 * @return
 */
public BigDecimal dividedByAndResultAsBigDecimal(EffortDuration other) {
    return other.isZero() ? BigDecimal.ZERO
            : new BigDecimal(this.getSeconds()).divide(new BigDecimal(other.getSeconds()), 8,
                    BigDecimal.ROUND_HALF_EVEN);
}

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static BigDecimal getBigDecimalForPercentageTag(BigDecimal amount) {
    if (amount == null) {
        return null;
    }/*  w  w w  .  jav a  2s . c  o  m*/
    return amount.setScale(PERCENTAGE_NUMBER_OF_DECIMALS, BigDecimal.ROUND_HALF_EVEN);
}